<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-08-11
 * @Time: 14:21
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Curriculum.php
 */
namespace app\api\model\curriculum;

use app\admin\model\PageResponse;
use app\admin\model\SysAdmin;
use app\common\model\CourseBindService;
use app\common\model\curriculum\CurriculumVideo;
use app\common\model\teacher\Teacher as TeacherAdmin;
use app\api\model\Teacher;
use app\api\model\user\Users;
use app\common\lib\pay\IBuyItem;
use app\common\model\BuyBill;
use app\common\model\dynamic\DynamicFlowItem;
use app\common\model\dynamic\DynamicFlowItemTeacher;
use app\common\model\DynamicFlow;
use app\common\model\Sales;
use app\common\model\zds\Order;
use app\common\utils\ObjectUtil;
use Curl\Curl;
use library\IntConvert;
use think\Cache;
use think\Db;
use think\Exception;
use think\Log;
use think\Model;
use think\Request;
use think\Validate;

/**
 * Class Curriculum
 * @package app\common\model\curriculum
 *
 * @property integer curriculum_id
 * @property integer curriculum_class
 * @property string curriculum_name
 * @property string curriculum_description
 * @property string curriculum_pic
 * @property integer curriculum_sales
 * @property integer curriculum_addtime
 * @property integer curriculum_updatetime
 * @property string curriculum_sale_price
 * @property string curriculum_market_price
 * @property string curriculum_icon
 * @property boolean hide
 * @property string curriculum_summary
 * @property integer curriculum_type
 * @property integer curriculum_level
 * @property integer curriculum_suit_user
 * @property integer curriculum_episode_number
 * @property double comment_score
 * @property integer sales_volume
 * @property integer credit_cost
 * @property integer enable_pay_type
 * @property boolean service_enable
 * @property string apple_pay_price
 * @property string apple_pay_production_id
 *
 */
class Curriculum extends Model {

    protected $table = 'curriculum';
    protected $pk = 'curriculum_id';
    protected $field = self::SaveFields;

    const SaveFields = [
        'curriculum_class',
        'curriculum_name',
        'curriculum_description',
        'curriculum_pic',
        'curriculum_sales',
        'curriculum_addtime',
        'curriculum_updatetime',
        'curriculum_sale_price',
        'curriculum_market_price',
        'curriculum_icon',
        'curriculum_summary',
        'curriculum_type',
        'curriculum_level',
        'curriculum_suit_user',
        'buy_total',
        'video_view',
        'hide',
        'credit_cost',
        'enable_pay_type',
        'apple_pay_price',
        'apple_pay_production_id',
        'service_enable',
    ];
    public static function getSaveFields() : array {
        return self::SaveFields;
    }

    public static function manageList(int $limit, int $offset, int $class_id = 0, $keywords = null) :PageResponse {

        $filter = '';
        $params = ['limit' => $limit, 'offset' => $offset, ];

        if ($class_id > 0) {
            $filter .= ' AND c.curriculum_class=:class_id ';
            $params['class_id'] = $class_id;
        }
        if ($keywords) {
            $filter .= ' AND c.curriculum_name LIKE :kw ';
            $params['kw'] = "%$keywords%";
        }

        $sql = <<<SQL
SELECT c.*, s.sales_title, 
  cs.bind_column_id,cs.online_course,cs.fupan_answer,cs.exclusive_group,cs.stock_analysis_report,cs.expired,cs.article_reference,cs.article_report,
  (SELECT rec_id FROM recommend r WHERE c.curriculum_id=r.rec_item_id AND r.rec_item_type=2) 
FROM curriculum c
LEFT JOIN sales s ON s.sales_id=c.curriculum_sales
LEFT JOIN course_bind_service cs ON c.curriculum_id = cs.curriculum_id
WHERE TRUE {$filter}
ORDER BY c.curriculum_id DESC 
LIMIT :limit OFFSET :offset
SQL;
        $list = Db::query($sql, $params);

        $sql = <<<SQL
SELECT count(curriculum_id) as num FROM curriculum
WHERE TRUE {$filter}
SQL;
        unset($params['limit'], $params['offset']);
        $re = Db::query($sql, $params);
        $total = $re[0]['num'] ?? 0;

        return PageResponse::success($list, $total);
    }

    public static function names() {
        $sql = <<<SQL
SELECT curriculum_id AS id ,curriculum_name AS name, curriculum_sale_price price FROM curriculum 
SQL;
        $list = Db::query($sql);

        return $list;
    }

    public static function namesForBill($bindArticleColId=0) {
        $courseType = self::TYPE_ADVANCED;

        // zk 20180524 获取有课程服务且可绑定文章的课程查询条件
        switch ($bindArticleColId) {
            case config('course_serivce.internalReferenceId'):
                $where = "and cbs.article_reference=true";
                break;
            case config('course_serivce.researchReportId'):
                $where = "and cbs.article_report=true";
                break;
            default :
                $where = " and c.curriculum_type={$courseType} AND c.curriculum_sale_price>0";
        }

        $sql = <<<SQL
SELECT c.curriculum_id AS id ,c.curriculum_name AS name, c.curriculum_sale_price as price , c.curriculum_type
FROM curriculum as c
left join course_bind_service cbs on c.curriculum_id = cbs.curriculum_id
WHERE hide=false {$where}
order by c.curriculum_id desc
SQL;
        $list = Db::query($sql);

        foreach ($list as &$val) {
            $val['curriculum_type_name'] = self::$TypeNames[$val['curriculum_type']];
        }

        return $list;
    }

    /**
     * 检查分类是否使用了
     *
     * @param $class_id
     * @return bool
     */
    public static function classUsed($class_id) {
        $sql = <<<SQL
SELECT exists(SELECT * FROM curriculum WHERE curriculum_class=:class_id LIMIT 1) AS e
SQL;
        $re = Db::query($sql, ['class_id' => $class_id]);

        return $re[0]['e'] ?? false;
    }

    public static function checkPreviewVideo($id) {
        $sql = 'SELECT exists(select 1 from curriculum_video where video_curriculum=:cid AND preview_allowed) e';
        $re = Db::query($sql, ['cid' => $id]);
        return $re[0]['e'] ?? false;
    }

    /**
     * 设置隐藏属性
     * @param $id
     * @param $hide
     */
    public static function setHide($id, $hide) {
        $curriculum=Curriculum::where('curriculum_id',$id)->field('curriculum_type')->find();
        if (empty($curriculum)) return;
        $is_free=$curriculum->curriculum_type==2 ? true : false;
        $type=$curriculum->curriculum_type;

        Db::transaction(function () use ($id,$hide,$is_free,$curriculum,$type) {
            $sql = <<<SQL
UPDATE curriculum SET hide = :hide WHERE curriculum_id = :id RETURNING *
SQL;
            $re = Db::query($sql, ['id' => $id, 'hide' => $hide]);
            if (empty($re)) return;

            /**
             * @var static $model
             */
            $model = ObjectUtil::assign(static::class, $re[0]);

            if ($hide) {
                DynamicFlow::del(DynamicFlow::CLASS_CURRICULUM, $model->curriculum_id);
            } else {
                if($type!=3){
                    $model->makeDynamicData(false,DynamicFlow::SOURCE_ADMIN,$is_free);
                }
            }
        });
    }

    /**
     * 统计计算课程的视频数
     * @param $id
     */
    public static function countVideos($id) {
        $sql = <<<SQL
UPDATE curriculum
SET curriculum_episode_number = (
  SELECT count(v.*) num
  FROM curriculum_video v
  WHERE v.video_curriculum = curriculum_id AND v.hide=FALSE 
)
WHERE curriculum_id = :id;
SQL;
        Db::execute($sql, ['id' => $id]);
    }

    /**
     * 产生老师动态
     *
     * @param bool $isNew
     * @param integer $source
     * @return DynamicFlow
     * @throws Exception
     */
    public function makeDynamicData(bool $isNew, int $source = DynamicFlow::SOURCE_SYSTEM,$is_free=false): DynamicFlow
    {
        $sql = 'select video_teacher tid from curriculum_video where video_curriculum=:cid AND hide=FALSE limit 1';
        $re = Db::query($sql, ['cid' => $this->curriculum_id]);
        if (empty($re)) {
            throw new Exception('课程没有视频上架');
        }
        $teacher = TeacherAdmin::get($re[0]['tid']);
        if (empty($teacher)) {
            throw new Exception('数据错误，不正确的老师id');
        }

        $dynamic = new DynamicFlow();
        $dynamic->df_time = time();
        $dynamic->df_source = $source;
        $dynamic->df_isfee = $is_free;
        $dynamic->df_isnew = $isNew;

        $item = new DynamicFlowItem();
        $item->item_id = (int) $this->curriculum_id;
        $item->item_title = $this->curriculum_name;
        $item->item_cover = $this->curriculum_pic;
        $item->item_summary = $this->curriculum_summary;

        $item_teacher = new DynamicFlowItemTeacher();
        $item_teacher->teacher_id = (int) $teacher->id;
        $item_teacher->teacher_name = $teacher->realname;
        $item_teacher->teacher_avatar = $teacher->avatar ?? TeacherAdmin::DEFAULT_AVATAR;
        $item_teacher->teacher_degree = $teacher->getDegreeName();
        $item->item_teacher = $item_teacher;

        $dynamic->df_class = DynamicFlow::CLASS_CURRICULUM;
        $dynamic->df_type = DynamicFlow::TYPE_CURRICULUM;

        $dynamic->df_value = $item;

        $dynamic->save();

        return $dynamic;
    }


    private static $Model = null;
    /**
     * @return null|static
     */
    public static function model() {
        if (null == self::$Model) {
            self::$Model = new static();
        }
        return self::$Model;
    }

    const LEVEL_PRIMARY = 1;
    const LEVEL_INTERMEDIATE = 2;
    const LEVEL_SENIOR = 3;
    public static $LevelNames = [
        self::LEVEL_PRIMARY         => '初级',
        self::LEVEL_INTERMEDIATE    => '中级',
        self::LEVEL_SENIOR          => '高级',
    ];

    const TYPE_ADVANCED = 1;
    const TYPE_OPEN     = 2;
    const TYPE_VIP      = 3;
    public static $TypeNames = [
        self::TYPE_ADVANCED => '高级课',
        self::TYPE_OPEN     => '公开课',
        self::TYPE_VIP      => 'VIP课程',
    ];

    const PAY_TYPE_CASH = 1;
    const PAY_TYPE_CREDIT = 2;
    public static $PayTypeNames = [
        self::PAY_TYPE_CASH     => '现金购买',
        self::PAY_TYPE_CREDIT   => '积分兑换',
    ];


    /**
     * isBuy
     * 查询用户是否购买课程
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $uid 用户id
     * @param int $curriculum_id 课程id
     *
     * @access private
     * @return int
     */
    private function isBuy($uid, $curriculum_id)
    {
        if (SysAdmin::checkAdminUser($uid)) return 1;
        /*$result  = Db::table('user_buy_curriculum')
            ->where('uc_user', $uid)
            ->where('uc_curriculum', $curriculum_id)
            ->count('uc_id');*/

        $sql = <<<SQL
select count(uc_id) as uc_num from user_buy_curriculum where uc_user={$uid} and uc_curriculum={$curriculum_id};
SQL;
        $result = Db::query($sql);
        $result = $result[0]['uc_num'];

        if ($result) {
            return 1; // 已购买
        } else {
            return 0; // 未购买
        }
    }

    public static function haveBought($uid, $curriculum_id) {
        return self::model()->isBuy($uid, $curriculum_id);
    }

    public static function isOpen($curriculum_id) {
        return self::model()->isOpenCurriculum($curriculum_id);
    }


    /**
     * buyTotal
     * 统计课程购买数量
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $curriculum_id 课程id
     *
     * @access private
     * @return mixed
     */
    private function buyTotal($curriculum_id)
    {
        /*$result  = Db::table('user_buy_curriculum')
            ->where('uc_curriculum', $curriculum_id)
            ->count('uc_id');*/

        $sql = <<<SQL
select count(uc_id) as uc_num from user_buy_curriculum where uc_curriculum={$curriculum_id};
SQL;
        $result = Db::query($sql);

        return $result[0]['uc_num'];
    }

    /**
     * getTeacher
     * 获取单个课程的所有（不重复）主讲老师数据
     *
     * @param int $curriculum_id 课程id
     * @param string $field 需要查询的字段，默认为所有字段
     *              老师数据表别名 t
     *              老师标签数据表别名 td
     *
     * @access private
     * @return mixed
     */
    public static  function getTeacher($curriculum_id, $field='*')
    {
        /*$videoTeacher = Db::table('curriculum_video')
            ->where('video_curriculum', $curriculum_id)
            ->field('distinct video_id')
            ->column('video_teacher');

        // $videoTeacher = array_unique($videoTeacher);

        $teacher = Db::table('teacher')
            ->alias('t')
            ->join('teacher_degree td', 't.degree_id=td.id', 'LEFT')
            ->whereExists('id', $videoTeacher)
            ->field($field)
            ->select();*/

        $sql = <<<SQL
  select {$field} from teacher t 
  LEFT JOIN teacher_degree td ON (t.degree_id=td.id)
  where exists (
      select count(cv.video_id), cv.video_teacher from curriculum_video as cv 
      where cv.video_curriculum={$curriculum_id} and cv.video_teacher=t.id group by cv.video_teacher
  );
SQL;

        $teacher = Db::query($sql);

        return $teacher;
    }

    /**
     * getVideo
     * 获取单个课程的所有视频并按照难度等级划分
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $curriculum_id 课程id
     * @param int $uid 用户id
     * @param int $isUser 是否为用户数据
     *
     * @access private
     * @return array
     */
    private function getVideo($curriculum_id, $uid=0, $isUser=false)
    {
        $teacherM = new Teacher();

        $video_level = [1, 2, 3];

        $result = [];
        foreach ($video_level as $key=>$val) {
            // 视频等级转换
            switch ($val) {
                case 1:
                    $video_level = '初级';
                    break;
                case 2:
                    $video_level = '中级';
                    break;
                case 3:
                    $video_level = '高级';
                    break;
            }

            // 查询视频等级锁定状态
            /*$level_query = Db::table('user_buy_curriculum_level')
                ->where('ucl_curriculum', $curriculum_id)
                ->where('ucl_user', $uid)
                ->where('ucl_level', $val)
                ->field('ucl_id, ucl_level_lock')
                ->find();*/
            $levelSQL = <<<SQL
select ucl_id, ucl_level_lock from user_buy_curriculum_level where ucl_curriculum={$curriculum_id} and ucl_user={$uid} and ucl_level={$val}
SQL;
            $level_query = Db::query($levelSQL);
            if ($level_query) {
                $level_query = $level_query[0];
            } else {
                $level_query = ['ucl_level_lock'=>0];
            }


            // 获取视频数据
            /*$video = Db::table('curriculum_video')
                ->where('video_curriculum', $curriculum_id)
                ->where('video_level', $val)
                ->field('
                    video_id,
                    video_sort,
                    video_title,
                    video_teacher,
                    video_cover,
                    video_url,
                    video_views,
                    video_isfree,
                    video_free_start_time,
                    video_free_end_time
                ')
                ->order('video_sort asc, video_addtime desc')
                ->select();*/

            if ($isUser) {
                $videoSQL = <<<SQL
select video_id,video_sort,video_title,video_teacher,video_cover,video_url,video_views,video_isfree,video_free_start_time,video_free_end_time from curriculum_video
where video_curriculum={$curriculum_id} and video_level={$val} order by video_sort asc, video_addtime desc
SQL;
            } else {
                $videoSQL = <<<SQL
select video_id,video_sort,video_title,video_teacher,video_cover,video_url,video_views,video_isfree,video_free_start_time,video_free_end_time from curriculum_video
where video_curriculum={$curriculum_id} and video_level={$val} and hide='false' order by video_sort asc, video_addtime desc
SQL;
            }
            $video = Db::query($videoSQL);

            $video_data = [];
            foreach ($video as $v_key=>$v_val) {
                // 获取老师数据
                $teacher = $teacherM->get_single_teacher($v_val['video_teacher']);
                $v_val['teacher_id'] = $teacher['id']; // 老师ID
                $v_val['video_teacher'] = $teacher['realname']; // 老师名称

                // 免费视频标识
                switch ($v_val['video_isfree']) {
                    case 1:
                        $v_val['video_is_free'] = 1;
                        break;
                    case 2:
                        if (time()>=$v_val['video_free_start_time'] && $v_val['video_free_end_time']<=time()) {
                            $v_val['video_is_free'] = 2;
                        } else {
                            $v_val['video_is_free'] = 0;
                        }
                        break;
                    default :
                        $v_val['video_is_free'] = 0;
                }

                unset($v_val['video_isfree']);

                $video_data[] = $v_val;
            }

            $result[] = [
                'video_level' => $video_level,
                'video_level_flag' => $val,
                'level_lock_status' => $level_query['ucl_level_lock'],
                'video_list' => $video_data
            ];
        }
        return $result;
    }

    /**
     * videoTotal
     * 统计单个课程所包含的视频总个数
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $curriculum_id 课程id
     *
     * @access private
     * @return mixed
     */
    private function videoTotal($curriculum_id)
    {
        /*$result = Db::table('curriculum_video')
            ->where('video_curriculum', $curriculum_id)
            ->count('video_id');*/

        $sql = <<<SQL
select count(video_id) as video_total from curriculum_video where video_curriculum={$curriculum_id} and hide='false'
SQL;
        $result = Db::query($sql);

        return $result[0]['video_total'];
    }

    /**
     * videoStudyStatus
     * 查询视频的学习状态
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $uid 用户id
     * @param int $buy_user_curriculum_id 用户购买课程记录id
     * @param int $buy_user_curriculum_level_id 用户购买课程难度等级记录id
     * @param int $curriculum_id 课程id
     * @param int $video_id 视频id
     * @param int $video_level 课程视频难度等级
     *
     * @access private
     * @return int
     */
    private function videoStudyStatus($uid, $buy_user_curriculum_id, $buy_user_curriculum_level_id, $curriculum_id, $video_id, $video_level)
    {
        // 查询已购买课程视频学习记录标识视频学习状态
        $study_query = Db::table('user_study_video')
            ->where('usv_user', $uid)
            ->where('usv_user_buy_curriculum', $buy_user_curriculum_id)
            ->where('usv_user_buy_curriculum_level', $buy_user_curriculum_level_id)
            ->where('usv_curriculum', $curriculum_id)
            ->where('usv_video_level', $video_level)
            ->where('usv_video', $video_id)
            ->field('usv_study_status')
            ->find();

        if ($study_query) {
            switch ($study_query['usv_study_status']) {
                case 1:
                    return 1;
                    break;
                case 2:
                    return 2;
                    break;
                default :
                    return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * commentTotal
     * 课程视频评价数量统计
     *
     * @author zhengkai
     * @date 2017-09-08
     * @update 2017-11-08 只统计课程的评论数
     *
     * @param int $curriculum_id
     * @param int $video_id
     *
     * @access private
     * @return int|string
     */
    private function commentTotal($curriculum_id, $video_id=0)
    {
        /*$result = Db::table('curriculum_comment')
            ->where('comment_curriculum', $curriculum_id)
            ->where('comment_video', $video_id)
            ->count('comment_id');*/
        $result = Db::query("select count(comment_id) as comment_num from curriculum_comment where comment_curriculum={$curriculum_id}");

        return $result[0]['comment_num'];
    }

    /**
     * get_single_curriculum
     * 获取指定id的单条课程数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $curriculum_id 课程id
     *
     * @access private
     * @return array|false|\PDOStatement|string|Model
     */
    private function get_single_curriculum($curriculum_id)
    {
        /*$result = $this->where('curriculum_id', $curriculum_id)->find();*/

        $result = Db::query("select * from curriculum where curriculum_id={$curriculum_id}");

        return $result[0];
    }

    /**
     * viewTotal
     * 单个课程视频观看总数统计
     *
     * @author zhengkai
     * @date 2017-11-07
     * @version v1.1
     *
     * @param int $curriculum_id 课程id
     *
     * @access private
     * @return mixed
     */
    private function viewTotal($curriculum_id)
    {
        $result = Db::query("select sum(video_views) as view_total from curriculum_video where video_curriculum={$curriculum_id}");

        return $result[0]['view_total'];
    }

    /**
     * $curriculumId
     * 获取课程的一个试看视频
     *
     * @author zhengkai
     * @date 2017-11-08
     *
     * @param int $curriculumId 课程id
     *
     * @access private
     * @return mixed
     */
    private function tryVideo($curriculumId)
    {
        $data = Db::query("select video_id,video_title,video_url,video_cover from curriculum_video where video_curriculum={$curriculumId} and preview_allowed='true'");
        $result = $data?$data[0]:(object)[];
        // $data = Db::query("select video_id from curriculum_video where video_curriculum={$curriculumId} and preview_allowed='true'");
        // $result = $data?$data[0]['video_id']:'';

        return $result;
    }

    /**
     * isComment
     * 查询课程的评价状态
     *
     * @author zhengkai
     * @date 2017-11-08
     *
     * @param int $uid 用户id
     * @param int $curriculumId 课程id
     *
     * @access private
     * @return int
     */
    private function isComment($uid, $curriculumId)
    {
        $sql = <<<SQL
SELECT exists(
select comment_id as num from curriculum_comment where comment_user=:uid and comment_curriculum=:curr_id
) e
SQL;
        $data = Db::query($sql, ['uid' => $uid, 'curr_id' => $curriculumId,]);
        return $data[0]['e'] ? 1 : 0;
    }

    /**
     * isOpenCurriculum
     * 是否为公开课程
     *
     * @author zhengkai
     * @date 2017-11-16
     *
     * @param int $curriculumId 课程id
     *
     * @access private
     * @return int
     */
    private function isOpenCurriculum($curriculumId)
    {
        $data = Db::query("select curriculum_type from curriculum where curriculum_id=:id",['id'=>$curriculumId]);
        $data = $data[0]['curriculum_type'];

        switch ($data) {
            case 2: // 公开课程
                return 1;
                break;
            default : // 默认高级课（收费课）
                return 0;
        }
    }

    /**
     * getFirstVideo
     * 获取课程的第一个视频
     *
     * @author zhengkai
     * @date 2017-11-16
     *
     * @param int $curriculumId 课程id
     *
     * @access private
     * @return object
     */
    private function getFirstVideo($curriculumId)
    {
        $data = Db::query("select video_id,video_title,video_url,video_cover from curriculum_video where video_curriculum={$curriculumId} order by video_sort asc limit 1");
        $result = $data?$data[0]:(object)[];

        return $result;
    }

    /**
     * isTryVideo
     * 是否为试看视频
     *
     * @author zhengkai
     * @date 2017-11-26
     *
     * @param int $videoId 视频id
     * @return int
     */
    protected function isTryVideo($videoId)
    {
        $sql = <<<SQL
select preview_allowed from curriculum_video where video_id={$videoId}
SQL;
        $data = Db::query($sql);

        if ($data[0]['preview_allowed']=='true') {
            return 1;
        } else {
            return 0;
        }
    }

    /**
     * getCurriculumPrice
     * 获取课程价格
     *
     * @author zhengkai
     * @date 2018-01-15
     *
     * @param int $id 课程id
     * @param int $type 价格类型 1=正常销售价格 2=促销价格
     * @return float|int|mixed
     */
    public static function getCurriculumPrice($id, $type=0) {
        $curriculum = Db::table('curriculum')
            ->field('curriculum_sale_price,curriculum_market_price,curriculum_sales')
            ->where('curriculum_id', $id)
            ->find();

        $now = time();
        if ($curriculum['curriculum_sales']>0) {
            $sales = Db::table('sales')
                ->where('sales_id', $curriculum['curriculum_sales'])
                ->where(function($query)use ($now){
                    $query->where('sales_start_time', '<', $now)
                        ->where('sales_end_time', '>', $now);
                })
                ->find();
            switch ($sales['sales_type']) {
                case 1: // 折扣
                    // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                    $curriculum['curriculum_market_price'] = $curriculum['curriculum_sale_price'];
                    $curriculum['curriculum_sale_price'] = round((((int)$sales['sales_discount']/100)*$curriculum['curriculum_sale_price']), 2);
                    break;
                case 2: // 减免金额
                    // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                    $curriculum['curriculum_market_price'] = $curriculum['curriculum_sale_price'];
                    $curriculum['curriculum_sale_price'] = ($curriculum['curriculum_sale_price']-$sales['sales_amount']);
                    break;
            }
        }

        return [
            'sale_price' => $curriculum['curriculum_sale_price'],
            'market_price' => $curriculum['curriculum_market_price']
        ];
    }

    /**
     * isVIP
     * 查询是否用户购买课程是否为VIP课程
     *
     * @author zhengkai
     * @date 2018-02-11
     *
     * @param $uid
     * @param $curriculumId
     * @return int|string
     */
    public static function isVIP($uid, $curriculumId)
    {
        $data = Db::table('zds_order o')
            ->join('buy_bill b','b.bill_id=o.billid','left')
            ->where('b.bill_item_type', 1)
            ->where('b.bill_have_paid', 'true')
            ->where('o.audit_status', 99)
            ->where('b.bill_user', $uid)
            ->where('b.bill_item_id', $curriculumId)
            ->count('o.id');

        return $data;
    }

    /**
     * get_all_curriculum
     * 获取全部课程数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $uid 用户id
     * @param int $page 当前页数
     * @param int $rows 每页获取数据条数
     * @return \think\response\Json
     */
    public function get_all_curriculum($uid, $page=1, $rows=10)
    {
        $this->where('hide', 'false');
        $this->field('
        curriculum_id, 
        curriculum_name, 
        curriculum_description, 
        curriculum_sale_price, 
        curriculum_market_price, 
        sales_volume,
        buy_total, 
        curriculum_episode_number video_total
        ');
        $data = $this->page($page, $rows)->select();

        foreach ($data as $key=>$val) {
            $val['curriculum_description'] = stripHtml($val['curriculum_description']);
            $val['is_buy'] = $this->isBuy($uid, $val['curriculum_id']);
            $val['teacher'] = self::getTeacher($val['curriculum_id'], 't.id, t.avatar');

            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$data));
    }

    /**
     * get_curriculum_detail
     * 获取课程详情数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $uid 用户id
     * @param int $curriculum_id 课程id
     * @return \think\response\Json
     */
    public function get_curriculum_detail($uid, $curriculum_id)
    {
        /*$curriculum = $this->where('curriculum_id', $curriculum_id)
            ->field('curriculum_id, curriculum_name, curriculum_description, curriculum_sale_price, curriculum_market_price')
            ->find();*/

        $curriculumSQL = <<<SQL
select curriculum_id, curriculum_name, curriculum_description, curriculum_sale_price, curriculum_market_price, curriculum_pic
 from curriculum where curriculum_id=:curriculum_id
SQL;
        $curriculum = Db::query($curriculumSQL, ['curriculum_id' => $curriculum_id]);
        $curriculum = $curriculum[0];


        // 课程是否购买标识
        $curriculum['is_buy'] = $this->isBuy($uid, $curriculum_id);

        // 该课程的所有主讲老师
        $curriculum['teacher'] = self::getTeacher($curriculum_id, '
            t.id as teacher_id, 
            t.realname as teacher_name, 
            td.name as teacher_degree, 
            t.avatar as teacher_avatar, 
            t.intro as teacher_intro,
            t.num_followed as teacher_follow,
            t.followed
        ');
        $teacher_data = [];
        foreach ($curriculum['teacher'] as $t_key=>$t_val) {
            $t_val['teacher_intro'] = stripHtml($t_val['teacher_intro']);
            $t_val['is_follow'] = Teacher::getFollowStatus($uid, $t_val['teacher_id']);

            $t_val['teacher_followed'] = countDataNum($t_val['teacher_followed'], $t_val['followed']);
            unset($t_val['followed']);

            $teacher_data[] = $t_val;
        }
        $curriculum['teacher'] = $teacher_data;

        // 该课程的所有视频
        $curriculum['video'] = $this->getVideo($curriculum_id, $uid);

        // 课程分享链接
        $curriculum['share_url'] = config('server.host').'/courseDetail?curriculum_id=15&bank=course';

        // 课程购买支付开关
        $curriculum['is_pay'] = config('isPay');

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$curriculum));
    }

    /**
     * get_buy_video
     * 获取已购买课程视频数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $uid 用户id
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条数
     * @return \think\response\Json
     *
     * TODO 测试性增加数据缓存，采用数组分页
     */
    public function get_buy_video($uid, $page=1, $rows=10)
    {
        $result = unserialize(Cache::tag('api_curriculum')->get('buy_video'));

        if ($result) {
            $result = page_array($rows, $page, $result, 0);
            return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
        }

        $video = Db::table('curriculum_video')
            ->alias('cv')
            ->join('user_buy_curriculum uc', 'cv.video_curriculum=uc.uc_curriculum', 'LEFT')
            ->join('buy_bill bb', 'uc.uc_bill=bb.bill_id', 'LEFT')
            ->join('curriculum c', 'cv.video_curriculum=c.curriculum_id', 'RIGHT')
            ->join('curriculum_class cc', 'c.curriculum_class=cc.class_id', 'RIGHT')
            ->where('uc.uc_user', $uid)
            ->field('
            cv.video_id,
            cc.class_name,
            cv.video_title,
            cv.video_level,
            cv.video_views,
            cv.views_total,
            cv.video_cover,
            cv.video_url,
            cv.video_isfree,cv.video_free_start_time,cv.video_free_end_time,cv.video_curriculum as curriculum_id, c.curriculum_name,
            uc.uc_id
            ')
            ->order('bb.bill_paytime desc')
            // ->page($page, $rows)
            ->select();

        $result = [];
        foreach ($video as $key=>$val) {
            $video_views = $val['video_views']>0?($val['views_total']+$val['video_views']):$val['views_total'];
            $val['video_views'] = num2tring($video_views);
            unset($val['views_total']);

            // 免费视频标识
            switch ($val['video_isfree']) {
                case 1:
                    $val['video_is_free'] = 1;
                    break;
                case 2:
                    if (time()>=$val['video_free_start_time'] && $val['video_free_end_time']<=time()) {
                        $val['video_is_free'] = 2;
                    } else {
                        $val['video_is_free'] = 0;
                    }
                    break;
                default :
                    $val['video_is_free'] = 0;
            }

            // 查询视频等级锁定状态
            $level_query= Db::table('user_buy_curriculum_level')
                ->where('ucl_user_buy_curriculum', $val['uc_id'])
                ->where('ucl_curriculum', $val['curriculum_id'])
                ->where('ucl_user', $uid)
                ->where('ucl_level', $val['video_level'])
                ->field('ucl_id, ucl_level_lock')
                ->find();
            $val['video_lock_status'] = $level_query['ucl_level_lock'];

            // 查询视频学习记录标识视频学习状态
            $val['video_study_status'] = $this->videoStudyStatus($uid, $val['uc_id'], $level_query['ucl_id'], $val['curriculum_id'], $val['video_id'], $val['video_level']);

            // 视频等级转换
            switch ($val['video_level']) {
                case 1:
                    $val['video_level'] = '初级';
                    break;
                case 2:
                    $val['video_level'] = '中级';
                    break;
                case 3:
                    $val['video_level'] = '高级';
                    break;
            }

            unset($val['video_isfree']);
            unset($val['video_free_start_time']);
            unset($val['video_free_end_time']);
            unset($val['uc_id']);

            $result[] = $val;
        }

        $result = array_sort($result, 'video_study_status', 'desc');
        $result = array_sort($result, 'video_lock_status', 'desc');

        Cache::tag('api_curriculum')->set('buy_video', serialize($result), 60);
        $result = page_array($rows, $page, $result, 0);

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_buy_curriculum
     * 获取已购买课程数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param $uid
     * @return \think\response\Json
     */
    public function get_buy_curriculum($uid)
    {
        $data = Db::table('user_buy_curriculum')
            ->alias('uc')
            ->join('curriculum c', 'uc.uc_curriculum=c.curriculum_id', 'LEFT')
            ->where('uc.uc_user', $uid)
            ->field('c.curriculum_id, c.curriculum_name, c.curriculum_icon, uc.uc_study_level as current_level')
            ->select();

        $result = [];
        foreach ($data as $key=>$val) {
            // 视频等级转换
            switch ($val['current_level']) {
                case 1:
                    $val['current_level'] = '初级';
                    break;
                case 2:
                    $val['current_level'] = '中级';
                    break;
                case 3:
                    $val['current_level'] = '高级';
                    break;
            }

            $result[] = $val;
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_buy_curriculum_detail
     * 获取已购买课程详情数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $uid 用户id
     * @param int $curriculum_id 课程id
     * @return \think\response\Json
     */
    public function get_buy_curriculum_detail($uid, $curriculum_id)
    {
        $curriculum = Db::table('user_buy_curriculum')
            ->alias('uc')
            ->join('curriculum c', 'uc.uc_curriculum=c.curriculum_id', 'LEFT')
            ->where('uc.uc_user', $uid)
            ->where('uc.uc_curriculum', $curriculum_id)
            ->find();

        $video = $this->getVideo($curriculum['uc_curriculum'], $uid, true);
        $video_list = [];
        foreach ($video as $key=>$val) {

            $video_arr = [];
            foreach ($val['video_list'] as $v_key=>$v_val) {
                // 查询视频等级锁定状态
                $level_query= Db::table('user_buy_curriculum_level')
                    ->where('ucl_user_buy_curriculum', $curriculum['uc_id'])
                    ->where('ucl_curriculum', $curriculum['uc_curriculum'])
                    ->where('ucl_user', $uid)
                    ->where('ucl_level', $val['video_level_flag'])
                    ->field('ucl_id')
                    ->find();

                // 视频学习状态
                $v_val['video_study_status'] = $this->videoStudyStatus($uid, $curriculum['uc_id'], $level_query['ucl_id'], $curriculum['uc_curriculum'], $v_val['video_id'], $val['video_level_flag']);

                unset($v_val['video_teacher']);
                unset($v_val['teacher_id']);
                unset($v_val['video_views']);

                $video_arr[] = $v_val;
            }

            $val['video_list'] = $video_arr;

            $video_list[] = $val;
        }

        $result = [
            'curriculum_id' => $curriculum['curriculum_id'],
            'curriculum_name' => $curriculum['curriculum_name'],
            'curriculum_video' => $video_list,
        ];

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_video_detail
     * 获取视频详情数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $video_id 视频id
     * @param int $uid 用户id
     * @return \think\response\Json
     */
    public function get_video_detail($video_id, $uid=0)
    {
        // 获取视频数据
        /*$data = Db::table('curriculum_video')
            ->where('video_id', $video_id)
            ->find();*/
        $data = Db::query("select * from curriculum_video where video_id={$video_id}");
        $data = $data[0];

        $data['video_views'] = countDataNum($data['video_views'], $data['views_total'], true);
        unset($data['views_total']);

        $data = [
            'curriculum_id' => $data['video_curriculum'],
            'teacher_id' => $data['video_teacher'],
            'video_id' => $data['video_id'],
            'video_level' => $data['video_level'],
            'video_title' => $data['video_title'],
            'video_cover' => $data['video_cover'],
            'video_description' => $data['video_description'],
            'video_url' => $data['video_url'],
            'video_views' => $data['video_views']
        ];

        // 获取老师数据
        $teacherM = new Teacher();
        $teacher = $teacherM->get_single_teacher($data['teacher_id']);
        $data['video_teacher'] = [
            'teacher_id' => $teacher['teacher_id'],
            'teacher_name' => $teacher['realname'],
            'teacher_sex' => $teacher['gender'],
            'teacher_degree' => $teacher['degree_name'],
            'teacher_intro' => $teacher['intro'],
            'teacher_follow' => countDataNum($teacher['num_followed'], $teacher['followed']),
            'teacher_avatar' => $teacher['avatar'],
            'teacher_follow_status' => $teacherM::getFollowStatus($uid, $teacher['teacher_id'])
        ];

        // 视频评价数量
        $data['comment_total'] = $this->commentTotal($data['curriculum_id'], $data['video_id']);
        $data['is_buy'] = $this->isBuy($uid, $data['curriculum_id']);

        // 更新课程视频观看次数
//        Db::table('curriculum_video')->where('video_id', $video_id)->update(['video_views'=>++$data['video_views']]);
        self::updateVideoViewCount($data['video_id']);
        self::updateCurriculumViewCount($data['curriculum_id']);

        $data['questions_url'] = config('server.host').'/static/questions/loginTest.html?timestamp='.time();

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$data));
    }

    /**
     * 累计课程视频观看总数
     *
     * @param $curriculumId
     */
    public static function updateCurriculumViewCount($curriculumId) {
        $sql = 'UPDATE curriculum SET view_total=view_total+1 WHERE curriculum_id=:curriculum_id';
        Db::execute($sql, ['curriculum_id' => $curriculumId]);
    }

    /**
     * 累计视频观看次数
     *
     * @param $videoId
     */
    public static function updateVideoViewCount($videoId) {
        $sql = 'UPDATE curriculum_video SET video_views=video_views+1 WHERE video_id=:video_id';
        Db::execute($sql, ['video_id' => $videoId]);
    }

    /**
     * get_related_video
     * 获取视频的相关视频数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $video_id 视频id
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条数
     * @return array
     */
    public function get_related_video($video_id, $page=1, $rows=10)
    {
        // 查询获取指定id的课程视频获取课程id、课程视频难度级别、课程视频适宜人群数据
        /*$video = Db::table('curriculum_video')
            ->where('video_id', $video_id)
            ->field('video_id, video_curriculum, video_level, video_user_level')
            ->find();*/
        $video = Db::query("select video_id, video_curriculum, video_level, video_user_level from curriculum_video where video_id={$video_id}");
        $video = $video[0];

        // 查询获取视频所属课程的分类
        /*$curriculum = $this->where('curriculum_id', $video['video_curriculum'])->field('curriculum_class')->find();*/
        $curriculum = Db::query("select curriculum_class from curriculum where curriculum_id={$video['video_curriculum']}");
        $curriculum = $curriculum[0];

        // 根据条件查询获取相关视频数据
        /*$data = Db::table('curriculum_video')
            ->alias('cv')
            ->join('curriculum c', 'cv.video_curriculum=c.curriculum_id', 'LEFT')
            ->join('teacher t', 'cv.video_teacher=t.id','LEFT')
            ->where('c.curriculum_class', $curriculum['curriculum_class'])
            ->where('cv.video_level', $video['video_level'])
            ->where('cv.video_user_level', $video['video_user_level'])
            ->where('cv.video_id', '<>', $video['video_id'])
            ->field('c.curriculum_id, cv.video_id, cv.video_title, cv.video_description, cv.video_cover, cv.video_views, t.realname')
            ->select();*/
        $sql = <<<SQL
select c.curriculum_id, cv.video_id, cv.video_title, cv.video_description, cv.video_cover, cv.video_views, cv.video_views, cv.views_total, cv.video_isfree, cv.video_free_start_time, cv.video_free_end_time, t.realname from curriculum_video cv
  LEFT JOIN curriculum c on (cv.video_curriculum=c.curriculum_id)
  LEFT JOIN teacher t on (cv.video_teacher=t.id)
where c.curriculum_class=:curriculum_class and
  cv.video_id<>:video_id and c.hide='false' and cv.hide='false'
order by cv.video_sort asc, cv.video_addtime desc
SQL;
        $data = Db::query($sql, [
            'curriculum_class' => $curriculum['curriculum_class'],
            'video_id' => $video['video_id'],
        ]);

        $result = [];
        foreach ($data as $key=>$val) {
            // 免费视频标识
            switch ($val['video_isfree']) {
                case 1:
                    $val['video_is_free'] = 1;
                    break;
                case 2:
                    if (time()>=$val['video_free_start_time'] && $val['video_free_end_time']<=time()) {
                        $val['video_is_free'] = 2;
                    } else {
                        $val['video_is_free'] = 0;
                    }
                    break;
                default :
                    $val['video_is_free'] = 0;
            }

            $val['video_views'] = countDataNum($val['video_views'], $val['views_total'], true);

            $result[] = [
                'curriculum_id' => $val['curriculum_id'], // 课程ID
                'video_id' => $val['video_id'], // 课程视频ID
                'video_title' => $val['video_title'], // 课程视频标题
                'video_description' => stripHtml($val['video_description']), // 课程视频描述
                'video_cover' => $val['video_cover'], // 课程视频封面图片
                'video_views' => $val['video_views'], // 课程视频被观看次数
                'video_is_free' => $val['video_is_free'], // 课程视频是否免费 0=否 1=完全 2=限时免费
                'teacher_name' => $val['realname'], // 课程视频主讲老师
            ];

            unset($val['views_total']);
            unset($val['video_isfree']);
            unset($val['video_free_start_time']);
            unset($val['video_free_end_time']);
        }
        $result = page_array($rows, $page, $result, 0);

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_free_video
     * 获取免费课程视频数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条数
     * @return \think\response\Json
     */
    public function get_free_video($page=1, $rows=10)
    {
        $data = Db::table('curriculum_video')
            ->alias('cv')
            ->join('curriculum c', 'cv.video_curriculum=c.curriculum_id', 'LEFT')
            ->join('teacher t', 'cv.video_teacher=t.id', 'LEFT')
            ->where('cv.video_isfree', 1)
            ->where('c.hide', 'false')
            ->where('cv.hide', 'false')
            ->whereOr(function ($query){
                $time = time();
                $query->where('cv.video_isfree', 2)->where('cv.video_free_start_time', '>=', $time)
                    ->where('cv.video_free_end_time', '<=', $time);
            })
            ->order('cv.video_curriculum desc, cv.video_sort asc')
            ->field('
                cv.video_curriculum as curriculum_id,
                cv.video_id,
                cv.video_title,
                cv.video_description,
                cv.video_cover,
                cv.video_views,
                cv.views_total,
                t.realname as teacher_name,
                cv.video_sort
            ')
            ->order('c.curriculum_class asc, video_sort asc, video_addtime desc')
            ->page($page, $rows)
            ->select();

        $result = [];
        foreach ($data as $key=>$val) {
            $val['video_description'] = stripHtml($val['video_description']);

            $val['video_views'] = countDataNum($val['video_views'], $val['views_total'], true);
            unset($val['views_total']);

            $result[] = $val;
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_teacher_video
     * 获取指定老师id的(免费)课程视频数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $teacher_id 老师id
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条数
     * @return \think\response\Json
     */
    public function get_teacher_video($teacher_id, $page=1, $rows=10)
    {
        $data = Db::table('curriculum_video')
            ->alias('cv')
            ->join('teacher t', 'cv.video_teacher=t.id', 'LEFT')
            ->where('cv.video_isfree', 1)
            ->where('cv.hide', 'false')
            ->whereOr(function ($query){
                $query->where('cv.video_isfree', 2)->where('cv.video_free_start_time', '>=', time())->where('cv.video_free_end_time', '<=', time());
            })
            ->where('t.id', $teacher_id)
            ->field('
                cv.video_curriculum as curriculum_id,
                cv.video_id,
                cv.video_title,
                cv.video_description,
                cv.video_cover,
                cv.video_views,
                cv.views_total,
                t.realname as teacher_name
            ')
            ->page($page, $rows)
            ->select();

        $result = [];
        foreach ($data as $key=>$val) {
            $val['video_description'] = stripHtml($val['video_description']);

            $val['video_views'] = countDataNum($val['video_views'], $val['views_total'], true);
            unset($val['views_total']);

            $result[] = $val;
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_teacher_curriculum
     * 获取指定老师id的所有课程（与该老师相关的课程）数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $teacher_id 老师id
     * @param int $uid 用户id
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条数
     * @return \think\response\Json
     */
    public function get_teacher_curriculum($teacher_id, $uid=0, $page=1, $rows=10,$isPc=false)
    {
        // 通过老师id查询出视频数据中包含该老师的所有课程id
        $sql = <<<SQL
select count(video_id),video_curriculum from curriculum_video where video_teacher=:teacher_id group by video_curriculum
SQL;
        $video = Db::query($sql, ['teacher_id' => $teacher_id]);
        $video_teacher = '';
        foreach ($video as $val) {
            $video_teacher .= $val['video_curriculum'].',';
        }
        if ($video) {
            $curriculumId = rtrim($video_teacher, ',');
        } else {
            $curriculumId = 0;
        }

        // 通过取得的课程id获取课程数据
        $curriculumM = Db::table('curriculum c');
        $curriculumM->join('curriculum_class cc','c.curriculum_class=cc.class_id','left');
        $curriculumM->join('sales ss','c.curriculum_sales=ss.sales_id','left');
        $curriculumM->where('hide', 'false');
        $curriculumM->where('curriculum_type', '<>', 3);
        $curriculumM->where('curriculum_id', 'in', $curriculumId);
        $curriculumM->field('
        curriculum_id, 
        curriculum_name, 
        curriculum_description, 
        curriculum_sale_price, 
        curriculum_market_price, 
        sales_volume, 
        buy_total, 
        curriculum_episode_number video_total,
        curriculum_pic,
        curriculum_level,
        class_name as curriculum_class,
        curriculum_sales,
        ss.sales_type,
        ss.sales_discount,
        ss.sales_amount,
        ss.sales_start_time,
        ss.sales_end_time
        ');
        $curriculumM->order('curriculum_addtime desc');
        $data= $curriculumM->paginate($rows)->toArray();

        $result = [];
        $now = time();
        foreach ($data['data'] as $key=>$val) {
            $val['curriculum_description'] = stripHtml($val['curriculum_description']);
            $val['is_buy'] = $this->isBuy($uid, $val['curriculum_id']);
            if($isPc){
                $teacher = self::getTeacher($val['curriculum_id'], 't.id, t.realname');
                $val['teacher_id'] = $teacher[0]['id']??0;
                $val['teacher_name'] = $teacher[0]['realname']??'';
            }else{
                $val['teacher'] = self::getTeacher($val['curriculum_id'], 't.id, t.avatar');
            }

            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            unset($val['sales_volume']);
            $val['curriculum_level']=config('curriculum_level')[$val['curriculum_level']]??"";

            $sales_val = 0; // 活动优惠
            if ($val['curriculum_sales']>0 && ($val['sales_start_time']<=$now && $now<=$val['sales_end_time'])) {
                switch ($val['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(((int)$val['sales_discount']/10), 1).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$val['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$val['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$val['sales_amount']);
                        break;
                }
            }
            $val['curriculum_sales'] = $val['curriculum_sales']?$sales_val:0;
            unset($val['sales_type']);
            unset($val['sales_discount']);
            unset($val['sales_amount']);
            unset($val['sales_start_time']);
            unset($val['sales_end_time']);
            $result[] = $val;
        }
        if($isPc){
            $data['data']=$result;
            return json(array('code'=>200, 'msg'=>'success', 'data'=>$data));
        }else{
            return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
        }
    }

    /**
     * get_user_buy_curriculum
     * 获取用户已购买课程数据
     *
     * @author zhengkai
     * @date 2017-09-08
     * @update
     *      v1.3.1  20180211  zhengkai
     *          增加是否为VIP课程状态字段
     *
     * @param int $class_id 课程分类id 默认为0获取所有课程
     * @param int $uid 用户id
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条数
     * @return \think\response\Json
     */
    public function get_user_buy_curriculum($class_id=0, $uid, $page=1, $rows=10)
    {
        $this->alias('c');
        $this->join('user_buy_curriculum ubc', 'c.curriculum_id=uc_curriculum');
        $this->join('buy_bill b','b.bill_id=ubc.uc_bill');
        $this->join('curriculum_class cls','cls.class_id=c.curriculum_class','LEFT');
        if ($class_id) $this->where('c.curriculum_class', $class_id);
        $this->where('ubc.uc_user','=', $uid);
        $this->field('
        c.curriculum_id, 
        c.curriculum_name, 
        c.curriculum_pic, 
        c.curriculum_sales, 
        c.curriculum_summary, 
        c.curriculum_description, 
        c.curriculum_level,
        c.curriculum_suit_user,
        c.curriculum_sale_price, 
        c.curriculum_market_price,
        c.curriculum_sales,
        c.curriculum_episode_number as video_total,
        c.sales_volume,
        c.buy_total,
        c.view_total,
        c.video_view,
        b.bill_id,
        b.bill_pay_amount,
        b.bill_paytime as buy_time,
        cls.class_name curriculum_class,
        c.apple_pay_price,
        c.apple_pay_production_id
        ');
        $this->order('ubc.uc_id','DESC');
        $data = $this->page($page, $rows)->select();

        $now = time();
        foreach ($data as $key=>$val) {

            // 视频观看总数、课程销量处理
            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            $val['video_view'] = countDataNum($val['video_view'], $val['view_total'], true);
            unset($val['sales_volume'], $val['view_total']);

            $val['curriculum_description'] = stripHtml($val['curriculum_description']);
            $val['is_buy'] = 1;
            $val['is_vip'] = self::isVIP($uid, $val['curriculum_id'])?1:0;
            $val['teacher'] = self::getTeacher($val['curriculum_id'], 't.id, t.avatar,t.realname');
            $val['buy_time'] = date('Y-m-d', $val['buy_time']);
            $val['curriculum_level'] = self::$LevelNames[$val['curriculum_level']] ?? '';
            $val['curriculum_suit_user'] = Users::getUserLevelName($val['curriculum_suit_user']);

            $sales_val = 0; // 活动优惠
            if ($val['curriculum_sales']>0) {
                $sales[$key]=Db::table('sales')
                    ->where('sales_id', $val['curriculum_sales'])
                    ->where(function($query)use ($now){
                        $query->where('sales_start_time', '<', $now)
                            ->where('sales_end_time', '>', $now);
                    })
                    ->find();
                switch ($sales[$key]['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(($sales[$key]['sales_discount']/10), 1).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$sales[$key]['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$sales[$key]['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$sales[$key]['sales_amount']);
                        break;
                }
            }
            $val['curriculum_sales'] = $val['curriculum_sales']?$sales_val:0;
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$data));
    }

    /**
     * get_curriculum_class
     * 获取课程分类数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @return \think\response\Json
     */
    public function get_curriculum_class()
    {
        $result = Db::table('curriculum_class')
            ->field('class_id, class_name')
            ->order('class_sort desc, class_id asc')
            ->select();

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_recommend_video
     * 获取获取推荐视频数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $num 显示条数，默认2条
     * @return array|false
     */
    public function get_recommend_video($num = 2)
    {
        $result = Db::table('recommend')
            ->alias('rec')
            ->join('curriculum_video cv', 'rec.rec_item_id=cv.video_id', 'LEFT')
            ->join('curriculum c', 'cv.video_curriculum=c.curriculum_id', 'LEFT')
            ->join('curriculum_class cc', 'c.curriculum_class=cc.class_id', 'LEFT')
            ->join('teacher t', 'cv.video_teacher=t.id','LEFT')
            ->where('rec.rec_item_type', 1)
            ->where('c.hide', 'false')
            ->field('c.curriculum_id, cv.video_id,  cv.video_level, cv.video_title, cv.video_cover, cv.video_views,cv.views_total, t.realname')
            ->order('rec_time desc')
            ->limit($num)
            ->select();

        foreach ($result as &$val) {
            $val['video_views'] = countDataNum($val['video_views'], $val['views_total'], true);
            unset($val['views_total']);
        }

        return $result;
    }

    /**
     * get_recommend_curriculum
     * 获取推荐课程数据
     *
     * @author zhengkai
     * @date 2017-09-08
     *
     * @param int $num 获取数据条数，默认为2条
     * @return array
     */
    public function get_recommend_curriculum($num = 2)
    {
        $data = Db::table('recommend')
            ->alias('rec')
            ->join('curriculum c', 'rec.rec_item_id=c.curriculum_id', 'LEFT')
            ->join('curriculum_class cc', 'c.curriculum_class=cc.class_id', 'LEFT')
            ->where('rec.rec_item_type', 2)
            ->where('c.hide', 'false')
            ->field('
                c.curriculum_id,
                c.curriculum_name,
                c.curriculum_pic,
                c.curriculum_sales,
                c.curriculum_type
             ')
            ->order('rec_time desc')
            ->limit($num)
            ->select();

        $result = [];
        $now = time();
        foreach ($data as $key=>$val) {
            $sales_val = 0; // 活动优惠
            if (2 == $val['curriculum_type']) {
                $sales_val = '公开课';
            } elseif ($val['curriculum_sales']>0) {
                $sales[$key]=Db::table('sales')
                    ->where('sales_id', $val['curriculum_sales'])
                    ->where(function($query)use ($now){
                        $query->where('sales_start_time', '<', $now)
                            ->where('sales_end_time', '>', $now);
                    })
                    ->find();
                switch ($sales[$key]['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(($sales[$key]['sales_discount']/10),1).'折';
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$sales[$key]['sales_amount'];
                        break;
                }
            }

            $result[] = [
                'curriculum_id' => $val['curriculum_id'], // 课程ID
                'curriculum_name' => $val['curriculum_name'], // 课程名称
                'curriculum_pic' => $val['curriculum_pic'], // 课程图片
                'curriculum_sales' => $val['curriculum_sales']?$sales_val:0, // 课程优惠
            ];
        }

        return $result;
    }

    /**
     * insert_comment
     * 写入课程评价数据到数据库
     *
     * @author zhengkai
     * @date 2017-09-08
     * @update zhengkai 2017-11-08 version 1.1
     *      只针对课程评价，增加课程评分
     *      计算该课程的综合评价得分，并写入课程数据表
     *
     * @param int $uid 用户id
     * @param int $curriculum_id 课程id
     * @param int $video_id 视频id TODO 在v1.1中取消，仅在v1.0中支持
     * @param string $comment_content 评价内容
     * @param int $comment_score 课程评分
     * @return \think\response\Json
     */
    public function insert_comment($uid, $curriculum_id, $video_id=0, $comment_content, $comment_score=0)
    {
        // 查询是否当前用户是否已经对该课程进行过评论
        $sql = <<<SQL
select count(comment_id) as comment_count from curriculum_comment where comment_user=:uid and comment_curriculum=:curriculum_id
SQL;
        $isExist = Db::query($sql, ['curriculum_id'=>$curriculum_id,'uid'=>$uid]);
        if ($isExist[0]['comment_count']) return json(array('code'=>1012, 'msg'=>'您已发表过评论了！', 'data'=>null));

        $data = [
            'comment_user' => $uid,
            'comment_curriculum' => $curriculum_id,
            'comment_video' => $video_id, // TODO 废弃
            'comment_content' => $comment_content,
            'comment_score' => $comment_score,
            'comment_time' => time()
        ];

        $result = Db::table('curriculum_comment')->insert($data);

        if ($result) {
            // 计算课程评分总数平均数
            $avg = Db::query("select avg(comment_score) as comment_avg_score from curriculum_comment where comment_curriculum=:curriculum_id",
                ['curriculum_id'=>$curriculum_id]);
            $commentScoreTotal = $avg[0]['comment_avg_score'];

            // 计算课程评论最终综合得分，四舍五入保留一位小数
            $scoreTotal = round($commentScoreTotal, 1);

            // 更新课程评论分数
            Db::query("update curriculum set comment_score=:score where curriculum_id=:curriculum_id",
                ['curriculum_id'=>$curriculum_id,'score'=>$scoreTotal]);


            return json(array('code'=>200, 'msg'=>'评论提交成功！', 'data'=>null));
        } else {
            return json(array('code'=>1012, 'msg'=>'评论提交失败！', 'data'=>null));
        }
    }

    /**
     * get_comment
     * 获取课程评价数据
     *
     * @author zhengkai
     * @date 2017-08-14
     * @update zhengkai 2017-11-09 version 1.1
     *      只获取课程评价，增加评分字段
     *
     * @param int $curriculum_id 课程id
     * @param int $video_id 视频id TODO 在v1.1中取消，仅在v1.0中支持
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条数
     * @return \think\response\Json
     */
    public function get_comment($curriculum_id, $video_id=0, $page=1, $rows=10)
    {
        $data = Db::table('curriculum_comment')
            ->alias('co')
            ->join('users u', 'co.comment_user=u.id', 'LEFT')
            ->where('co.comment_curriculum', $curriculum_id)
            // ->where('co.comment_video', $video_id) TODO 在v1.1中取消
            ->order('co.comment_time desc')
            ->field('co.comment_id, co.comment_content, co.comment_score, co.comment_time, u.id as uid, u.mobile, u.nickname, u.avatar')
            ->page($page, $rows)
            ->select();

        $result = [];
        foreach ($data as $key=>$val) {
            // 用户没有头像时加载默认头像
            $val['nickname'] = ($val['nickname']?:mobile_hidden(substr($val['mobile'], 0, 11)))?:$val['uid'];
            // 用户没有昵称时加载默认昵称
            $val['avatar'] = $val['avatar']?:Users::defaultAvatar();

            // 格式化评价时间
            $val['comment_time'] = date('Y-m-d H:i:s', $val['comment_time']);

            unset($val['mobile']);

            $result[] = $val;
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * get_post_bill
     * 获取某个课程(视频)的晒单数据
     *
     * @author zhengkai
     * @date 2017-08-21
     *
     * @param int $curriculum_id 课程id
     * @param null $video_id 视频id
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条
     * @return array|\think\response\Json
     */
    public function get_post_bill($curriculum_id, $video_id, $page=1, $rows=10)
    {
        // 查询所有当前课程(视频)的晒单数据
        $data = Db::table('curriculum_post_bill')
            ->alias('cpb')
            ->join('curriculum_video cv', 'cpb.bill_video=cv.video_id')
            ->where('cpb.bill_curriculum', $curriculum_id)
            ->where('cpb.bill_video', $video_id)
            ->order('cpb.bill_time desc')
            ->page($page, $rows)
            ->select();

        $result = [];
        foreach ($data as $key=>$val) {
            $result[] = [
                'curriculum_id'=>$val['bill_curriculum'], // 课程id
                'video_id'=>$val['video_id'], // 课程视频id
                'video_title'=>$val['video_title'], // 课程视频标题（名称）
                'video_description'=>stripHtml($val['video_description']), // 课程视频描述
                'bill_trading_day'=>$val['bill_trading_day'], // 交易日
                'bill_income'=>$val['bill_income'], // 交易日收益百分比
                'bill_stock_code'=>$val['bill_stock_code'], // 股票代码
                'bill_stock_name'=>$val['bill_stock_name'] // 股票名称
            ];
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * update_buy_curriculum_unlock
     * 更新用户已购买课程难度等级锁定状态
     *
     * @author zhengkai
     * @date 2017-09-11
     *
     * @param int $uid 用户id
     * @param int $curriculum_id 课程id
     * @param int $curriculum_level 课程视频难度等级id
     * @return \think\response\Json
     */
    public function update_buy_curriculum_unlock($uid, $curriculum_id, $curriculum_level)
    {
        // 查询已购买课程数据
        $buy_curriculum = Db::table('user_buy_curriculum')
            ->where('uc_curriculum', $curriculum_id)
            ->where('uc_user', $uid)
            ->field('uc_id')
            ->find();

        // 更新课程视频难度等级解锁状态
        $buy_curriculum_level = Db::table('user_buy_curriculum_level')
            ->where('ucl_user_buy_curriculum', $buy_curriculum['uc_id'])
            ->where('ucl_level', $curriculum_level)
            ->where('ucl_level_lock', 1)
            ->update([
                'ucl_level_lock' => 2,
                'ucl_unlock_time' => time()
            ]);

        if ($buy_curriculum_level) {
            // 更新已购买课程正在学习的课程视频难度等级
            Db::table('user_buy_curriculum')
                ->where('uc_curriculum', $curriculum_id)
                ->where('uc_user', $uid)
                ->setField('uc_study_level', $curriculum_level);

            return json(array('code'=>200, 'msg'=>'success', 'data'=>null));
        } else {
            return json(array('code'=>1012, 'msg'=>'fail', 'data'=>null));
        }
    }

    /**
     * 用户已购买课程视频学习状态数据处理（更新或新增）
     *
     * @author zhengkai
     * @date 2017-09-11
     *
     * @param int $uid 用户id
     * @param int $curriculum_id 课程id
     * @param int $video_id 视频id
     * @param int $curriculum_level 课程视频难度等级
     * @return \think\response\Json
     */
    public function  update_buy_curriculum_video_study_status($uid, $curriculum_id, $video_id, $curriculum_level)
    {
        // 查询出已购买课程数据
        $buy_curriculum = Db::table('user_buy_curriculum')
            ->where('uc_curriculum', $curriculum_id)
            ->where('uc_user', $uid)
            ->find();

        if ($buy_curriculum) {
            // 查询出已购买课程等级数据
            $buy_curriculum_level = Db::table('user_buy_curriculum_level')
                ->where('ucl_user_buy_curriculum', $buy_curriculum['uc_id'])
                ->where('ucl_level', $curriculum_level)
                ->find();



            // 查询是否有用户的视频学习记录数据
            $study_status_count = Db::table('user_study_video')
                ->where('usv_user', $uid)
                ->where('usv_user_buy_curriculum', $buy_curriculum['uc_id'])
                ->where('usv_user_buy_curriculum_level', $buy_curriculum_level['ucl_id'])
                ->where('usv_curriculum', $curriculum_id)
                ->where('usv_video_level', $curriculum_level)
                ->where('usv_video', $video_id)
                ->count('usv_id');
            if ($study_status_count) {
                Db::table('user_study_video')
                    ->where('usv_user', $uid)
                    ->where('usv_user_buy_curriculum', $buy_curriculum['uc_id'])
                    ->where('usv_user_buy_curriculum_level', $buy_curriculum_level['ucl_id'])
                    ->where('usv_curriculum', $curriculum_id)
                    ->where('usv_video_level', $curriculum_level)
                    ->where('usv_video', $video_id)
                    ->where('usv_study_status', 0)
                    ->update([
                        'usv_study_status' => 1,
                        'usv_study_updatetime' => time(),
                    ]);
            } else {
                $data = [
                    'usv_user' => $uid,
                    'usv_user_buy_curriculum' => $buy_curriculum['uc_id'],
                    'usv_user_buy_curriculum_level' => $buy_curriculum_level['ucl_id'],
                    'usv_curriculum' => $curriculum_id,
                    'usv_video_level' => $curriculum_level,
                    'usv_video' => $video_id,
                    'usv_study_status' => 1,
                    'usv_study_addtime' => time()
                ];

                Db::table('user_study_video')->insert($data);
            }

            return json(array('code'=>200, 'msg'=>'success', 'data'=>null));
        } else {
            return json(array('code'=>1012, 'msg'=>'课程未购买', 'data'=>null));
        }
    }

    /**
     * 用于支付的方法，购买支付后的处理
     *
     * @param $bill_id
     * @param $uid
     * @param $curriculum_id
     * @param $bill
     * @throws Exception
     */
    public static function afterBought($bill_id, $uid, $curriculum_id, BuyBill $bill) {
        // 查询课程是否为VIP课程
        $model = self::get($curriculum_id);

        switch ($model->curriculum_type) {
            case self::TYPE_VIP:
                // 创建销售系统订单
                Order::createOrder($bill->bill_id);
                $model->addUserBuyData($bill);
                $model->countSalesVolume();
                break;

            case self::TYPE_ADVANCED:
                // 高级课程订单流程
                $model->addUserBuyData($bill);
                $model->countSalesVolume();
                break;
        }
        /*if ($model->curriculum_type == self::TYPE_VIP) {
            // vip 课程订单流程
//            $postData = [
//                'uid' => $bill['bill_user'],
//                'bill_id' => $bill['bill_id'],
//                'order_no' => $bill['bill_no'],
//                'trade_no' => $bill['pay_trade_no'],
//                'item_type' => $bill['bill_item_type'],
//                'item_id' => $bill['bill_item_id'],
//                'pay_method' => $bill['bill_pay_method'],
//                'pay_amount' => $bill['bill_pay_amount'],
//                'trade_way' => $bill['bill_trade_way'],
//                'have_paid' => $bill['bill_have_paid'],
//                'create_time' => $bill['bill_createtime'],
//                'pay_time' => $bill['bill_paytime']
//            ];

            // 创建销售系统订单
            Order::createOrder($bill->bill_id);
            $model->addUserBuyData($bill);
            $model->countSalesVolume();

            // 远程通知VIP课程订单处理
//            $curl = new Curl();
//            $curl->post(config('server.vipUrl').'pay_callback', $postData);
//            $requestStatus = $curl->httpStatusCode;
//
//            if ($requestStatus==200 && 1==$curl->response) {
//            } else {
//                throw new Exception('连接销售系统失败',0);
//            }
        } else if ($model->curriculum_type == self::TYPE_ADVANCED) {
            // 高级课程订单流程
            $model->addUserBuyData($bill);
            $model->countSalesVolume();
        }*/
    }

    /**
     * addUserBuyData
     * 添加用户购买数据
     *
     * @param BuyBill $bill
     */
    private function addUserBuyData(BuyBill $bill) {
        $now = time();

        $sql = <<<SQL
INSERT INTO user_buy_curriculum (uc_curriculum, uc_bill, uc_user, service_expired) 
VALUES (:uc_curriculum, :uc_bill, :uc_user, :service_expired)
RETURNING uc_id
SQL;
        $params = [
            'uc_bill' => $bill->bill_id,
            'uc_user' => $bill->bill_user,
            'uc_curriculum' => $this->curriculum_id,
            'service_expired' => 0
        ];

        if ($this->service_enable) {
            $service = CourseBindService::get($this->curriculum_id);
            if ($service) {
                $params['service_expired'] = $now + $service->getSeconds();
            }
        }

        $re = Db::query($sql, $params);
        $uc_id = $re[0]['uc_id'];

        $data = [];
        foreach ([1, 2, 3] as $val) {
            $data[] = [
                'ucl_user_buy_curriculum' => $uc_id,
                'ucl_curriculum' => $this->curriculum_id,
                'ucl_user' => $bill->bill_user,
                'ucl_level' => $val,
                'ucl_level_lock'=>2, // zk 20171024 用户成功购买课程后，课程所有难度级别视频都设置为解锁可观看状态
                'ucl_unlock_time' => $now,
            ];
        }
        Db::table('user_buy_curriculum_level')->insertAll($data);
    }

    /**
     * countSalesVolume
     * 更新销量统计
     */
    private function countSalesVolume() {
        $sql = 'UPDATE curriculum SET sales_volume = sales_volume + 1, buy_total = buy_total + 1 WHERE curriculum_id=:id';
        Db::execute($sql, ['id' => $this->curriculum_id]);
    }

    /**
     * 用于支付的方法，计算商品总价格、获取商品信息等
     *
     * @param $uid
     * @param $curriculum_id
     * @return array|bool
     */
    public static function getBuyInfo($uid, $curriculum_id) {
        // 获取课程
        $curriculum = Db::table('curriculum')
            ->where('curriculum_id','=', $curriculum_id)
            ->field('curriculum_sale_price, curriculum_sales, curriculum_name, credit_cost,enable_pay_type,apple_pay_price,apple_pay_production_id')
            ->find();
        if (empty($curriculum)) {
            return false;
        }
        $price = $price_orig = $curriculum['curriculum_sale_price'];

        // 优惠活动
        $detail = "价格￥{$price}。";
        $result = [
            'price_orig' => $price_orig,
            'price' => $price,
            'title' => "课程《{$curriculum['curriculum_name']}》",
            'detail' => $detail,
            'credit_cost' => $curriculum['credit_cost'],
            'enable_pay_type' => $curriculum['enable_pay_type'],
            'apple_pay_price' => $curriculum['apple_pay_price'],
            'apple_pay_production_id' => $curriculum['apple_pay_production_id'],
        ];


        if ($curriculum['curriculum_sales'] > 0) {
            $sales = Sales::get($curriculum['curriculum_sales']);
            if ($sales && $sales->isAvailable()) {
                $re = $sales->finalPrice($price, $detail);
                $result['price'] = $re['price'];
                $result['detail'] = $re['detail'];
                $result['gifts'] = $re['gifts'];
            }
        }

        // 会员优惠
        //

        return $result;
    }

    /**
     * 检查是否购买
     * @param $uid
     * @param $curriculum_id
     * @return bool|mixed
     */
    public static function checkBought($uid, $curriculum_id) {
        $sql = <<<SQL
SELECT exists(SELECT 1 FROM user_buy_curriculum WHERE uc_user=:uid AND uc_curriculum=:cid) AS e
SQL;
        $re = Db::query($sql, ['uid'=>$uid,'cid'=>$curriculum_id]);
        $re = $re[0]['e'] ?? false;

        return $re;
    }

    public static function getSimpleList($ids) {
        return self::whereIn('curriculum_id',$ids)->field('curriculum_id,curriculum_name')->select();
    }

    /**
     * 获取购买的用户id列表
     *
     * @param $id
     * @return array
     */
    public static function getBoughtUsersID($id) {
        $sql = 'select uc_user AS uid from user_buy_curriculum where uc_curriculum=:id';
        $list = Db::query($sql, ['id' => $id]);
        return array_column($list, 'uid');
    }

    /**
     * queryNewCurriculum
     * 获取最新课程数据
     *
     * @author zhengkai
     * @date 2017-11-07
     * @version 1.1
     *
     * @param int $num 获取的数据条数
     * @return \think\response\Json
     */
    public function queryNewCurriculum($num=6)
    {
        $sql = <<<SQL
select curriculum_id,curriculum_name,curriculum_pic,curriculum_type,curriculum_sales,sales_volume,buy_total,view_total,video_view 
from curriculum where hide=false 
order by curriculum_addtime desc 
limit :num
SQL;
        $data = Db::query($sql, ['num' => $num]);

        $now = time();
        $arr = [];
        foreach ($data as $key=>$val) {
            // 课程销量处理
            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            // 视频观看总数处理
            $val['view_total'] = countDataNum($val['video_view'], $val['view_total'], true);

            $sales_val = 0; // 活动优惠
            if ($val['curriculum_sales']>0) {
                $sales[$key]=Db::table('sales')
                    ->where('sales_id', $val['curriculum_sales'])
                    ->where(function($query)use ($now){
                        $query->where('sales_start_time', '<', $now)
                            ->where('sales_end_time', '>', $now);
                    })
                    ->find();
                switch ($sales[$key]['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(($sales[$key]['sales_discount']/10), 1).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$sales[$key]['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$sales[$key]['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$sales[$key]['sales_amount']);
                        break;
                }
            }
            $val['curriculum_sales'] = $val['curriculum_sales']?$sales_val:0;

            $teacher = self::getTeacher($val['curriculum_id'], 't.realname');
            $val['curriculum_teacher'] = $teacher?$teacher[0]['realname']:"";

            unset($val['sales_volume'], $val['video_view']);
            $arr[] = $val;
        }
        $result = $arr;

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * filterCurriculumCondition
     * 获取课程筛选条件数据
     *
     * @author zhengkai
     * @date 2017-11-07
     * @version 1.1
     *
     * @return \think\response\Json
     */
    public function filterCurriculumCondition()
    {
        // 课程类型
        $type = array(
            ['name'=>'公开课', 'value'=>2],
            ['name'=>'vip课程', 'value'=>3],
        );

        // 课程分类
        $class = Db::query("select class_id, class_name from curriculum_class order by class_sort desc,class_id asc");

        // 老师
        $teacher = Db::query("select id as teacher_id,realname as teacher_name from teacher order by id asc");

        $result = array(
            'curriculum_type' => $type,
            'curriculum_class' => $class,
            'curriculum_teacher' => $teacher
        );

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * queryCurriculum
     * 根据条件查询课程数据
     *
     * @author zhengkai
     * @date 2017-11-07
     * @version 1.1
     * @update wangxuejiao 2018-04-17
     *         优化代码 修改分页
     *
     * @param int $uid 用户id
     * @param int $rows 每页显示数据条数
     * @param int $page 当前第x页
     * @return \think\response\Json
     */
    public function queryCurriculum($uid, $param=[])
    {
        $filter_param = $param;

        $page=isset($param['page'])?$param['page']:1;
        $rows=isset($param['rows'])?$param['rows']:10;

        $params = ['limit' => $rows, 'offset' => intval(($page - 1) * $rows)];

        switch ($filter_param['sort'] ?? null) {
            // 默认排序
            case 'asc':
                $order = 'c.curriculum_addtime asc';
                break;
            // 评价分数排序
            case 'score_asc':
                $order =  'c.comment_score asc';
                break;
            case 'score_desc':
                $order =  'c.comment_score desc';
                break;

            // 销量排序
            case 'sales_asc':
                $order = 'c.buy_total asc';
                break;
            case 'sales_desc':
                $order = 'c.buy_total desc';
                break;

            // 视频观看数排序
            case 'view_asc':
                $order = 'c.view_total asc';
                break;
            case 'view_desc':
                $order = 'c.view_total desc';
                break;

            // 课程难度等级排序
            case 'level_asc':
                $order =  'c.curriculum_level asc';
                break;
            case 'level_desc':
                $order =  'c.curriculum_level desc';
                break;
            case 'price_asc':
                $order= 'c.curriculum_sale_price asc';
                break;
            case 'price_desc':
                $order='c.curriculum_sale_price desc';
                break;
            case 'ios_price_asc':
                $order= 'c.apple_pay_price asc';
                break;
            case 'ios_price_desc':
                $order='c.apple_pay_price desc';
                break;
            default :
                $order = 'c.curriculum_id desc';
        }

        $filter_param = Request::instance()->param();
        //modify cc 去掉高级课程
        $condition=[
            'c.curriculum_type'=>['in',[3,2]],
            'c.hide'=>'false'
        ];
        //查询条件
        if(!empty($filter_param['key'])){
            $condition['c.curriculum_name|c.curriculum_summary']=['like','%'.$filter_param['key'].'%','_multi'=>true];
        }
        if(!empty($filter_param['class'])){
            $condition['c.curriculum_class']=$filter_param['class'];
        }
        if (!empty($filter_param['type'])) {
            $condition['c.curriculum_type']=$filter_param['type'];
        }
        // echo $filter_param['type'];
        if(!empty($filter_param['teacher'])){
            // 通过老师id查询出所有视频所对应的课程id
            $curriculumId= CurriculumVideo::where('video_teacher',$filter_param['teacher'])->distinct('video_curriculum')->column('video_curriculum');
            $condition['c.curriculum_id'] = empty($curriculumId) ? 0 : ['in',$curriculumId];
        }
        $data_temp = self::alias('c')
            ->join('curriculum_class cc', 'c.curriculum_class=cc.class_id', 'left')
            ->join('sales ss','c.curriculum_sales=ss.sales_id','left')
            ->field('
              c.curriculum_id,
              c.curriculum_name,
              c.curriculum_pic,
              c.curriculum_summary,
              c.curriculum_description,
              c.curriculum_sale_price,
              c.curriculum_market_price,
              c.curriculum_sales,
              c.curriculum_suit_user,
              c.curriculum_type,
              c.curriculum_level,
              cc.class_name as curriculum_class,
              c.sales_volume,
              c.buy_total,
              c.view_total,
              c.video_view,
              c.curriculum_episode_number as video_total,
              ss.sales_type,
              ss.sales_discount,
              ss.sales_amount,
              ss.sales_start_time,
              ss.sales_end_time,
              c.apple_pay_price,
              c.apple_pay_production_id
            ')
            ->where($condition)
            ->order($order)
            ->paginate($rows)->toArray();
        $data=$data_temp['data'];
        $pageTotal = $data_temp['last_page'];
        unset($data_temp);
        $now = time();
        foreach ($data as & $val) {
            // 课程销量处理
            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            // 视频观看总数处理
            $val['view_total'] = countDataNum($val['video_view'], $val['view_total'], true);

            $val['curriculum_summary'] = str_replace('&nbsp;', '', stripHtml($val['curriculum_summary']));
            $val['curriculum_description'] = str_replace('&nbsp;', '', stripHtml($val['curriculum_description']));

            switch ($val['curriculum_level']) {
                case 1:
                    $val['curriculum_level'] = '初级';
                    break;
                case 2:
                    $val['curriculum_level'] = '中级';
                    break;
                case 3:
                    $val['curriculum_level'] = '高级';
                    break;
            }

            $sales_val = 0; // 活动优惠
            if ($val['curriculum_sales']>0 && ($val['sales_start_time']<=$now && $now<=$val['sales_end_time'])) {
                switch ($val['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(((int)$val['sales_discount']/10), 1).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$val['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$val['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$val['sales_amount']);
                        break;
                }
            }
            $val['curriculum_sales'] = $val['curriculum_sales']?$sales_val:0;

            $teacher = self::getTeacher($val['curriculum_id'], 't.realname');
            $val['curriculum_teacher'] = $teacher?$teacher[0]['realname']:"";

            $val['is_buy'] = $this->isBuy($uid, $val['curriculum_id']);

            unset($val['sales_type'], $val['sales_discount'], $val['sales_amount'], $val['sales_start_time'], $val['sales_end_time'], $val['video_view'], $val['sales_volume']);
        }

        // 课程销售价格排序处理
//        if (isset($filter_param['sort']) && !empty($filter_param['sort']) && $filter_param['sort']=='price_asc') {
//            $data = array_sort($data, 'curriculum_sale_price', 'asc');
//        } else if (isset($filter_param['sort']) && !empty($filter_param['sort']) && $filter_param['sort']=='price_desc') {
//            $data = array_sort($data, 'curriculum_sale_price', 'desc');
//        }


        // 重组输出数组
        $result = [
            'page_total' => $pageTotal, // 总页数
            'list' => $data
        ];

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * queryCurriculumNew
     * 根据条件查询课程数据
     *
     * @author wangxuejiao
     * @date 2018-04-17
     * @version 1.4
     *
     * @param $uid
     * @param int $rows
     * @return \think\response\Json
     * @throws \think\exception\DbException
     */
    public function queryCurriculumNew($uid, $rows=10)
    {
        $filter_param = Request::instance()->param();
        $condition=[
            'c.curriculum_type'=>['in',[1,2]],
            'c.hide'=>'false'
        ];
        // 排序
        $order = 'c.curriculum_id desc';
        $sort=(isset($filter_param['sort']) && in_array($filter_param['sort'],['asc','desc']))? $filter_param['sort'] : 'desc';
        if(isset($filter_param['order_field']) && in_array($filter_param['order_field'],['curriculum_addtime','comment_score','buy_total','view_total','curriculum_level','curriculum_sale_price'])){
            $order='c.'.$filter_param['order_field'].' '.$sort;
        }
        //查询条件
        if(!empty($filter_param['key'])){
            $condition['c.curriculum_name|c.curriculum_summary']=['like','%'.$filter_param['key'].'%','_multi'=>true];
        }
        if(!empty($filter_param['class'])){
            $condition['c.curriculum_class']=$filter_param['class'];
        }
        if (!empty($filter_param['type'])) {
            $condition['c.curriculum_type']=$filter_param['type'];
        }
        if(!empty($filter_param['teacher'])){
            // 通过老师id查询出所有视频所对应的课程id
            $curriculumId= CurriculumVideo::where('video_teacher',$filter_param['teacher'])->distinct('video_curriculum')->column('video_curriculum');
            $condition['c.curriculum_id'] = empty($curriculumId) ? 0 : ['in',$curriculumId];
        }
        $result = self::alias('c')
            ->join('curriculum_class cc', 'c.curriculum_class=cc.class_id', 'left')
            ->join('sales ss','c.curriculum_sales=ss.sales_id','left')
            ->field('
              c.curriculum_id,
              c.curriculum_name,
              c.curriculum_pic,
              c.curriculum_summary,
              c.curriculum_description,
              c.curriculum_sale_price,
              c.curriculum_market_price,
              c.curriculum_sales,
              c.curriculum_suit_user,
              c.curriculum_type,
              c.curriculum_level,
              cc.class_name as curriculum_class,
              c.sales_volume,
              c.buy_total,
              c.view_total,
              c.video_view,
              c.curriculum_episode_number video_total,
              ss.sales_type,
              ss.sales_discount,
              ss.sales_amount,
              ss.sales_start_time,
              ss.sales_end_time,
              c.apple_pay_price,
              c.apple_pay_production_id
            ')
            ->where($condition)
            ->order($order)
            ->paginate($rows)
            ->toArray();

        $now = time();
        foreach ($result['data'] as & $val) {
            // 课程销量处理
            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            // 视频观看总数处理
            $val['view_total'] = countDataNum($val['video_view'], $val['view_total'], true);

            $val['curriculum_summary'] = str_replace('&nbsp;', '', stripHtml($val['curriculum_summary']));
            $val['curriculum_description'] = str_replace('&nbsp;', '', stripHtml($val['curriculum_description']));
            $val['curriculum_level']=config('curriculum_level')[$val['curriculum_level']];

            $sales_val = 0; // 活动优惠
            if ($val['curriculum_sales']>0 && ($val['sales_start_time']<=$now && $now<=$val['sales_end_time'])) {
                switch ($val['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(((int)$val['sales_discount']/10), 1).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$val['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$val['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$val['sales_amount']);
                        break;
                }
            }
            $val['curriculum_sales'] = $val['curriculum_sales']?$sales_val:0;
            //只展示第一个老师
            $teacher=Teacher::getRealName($val['curriculum_id']);
            $val['curriculum_teacher'] = $teacher?$teacher[0]:"";

            $val['is_buy'] = $this->isBuy($uid, $val['curriculum_id']);

            unset($val['sales_type'],$val['sales_discount'],$val['sales_amount'],$val['sales_start_time'],$val['sales_end_time'],$val['sales_volume'],$val['video_view']);
        }

        return $result;
    }

    /**
     * 查询积分商城的课程
     *
     * @param $page
     * @param $rows
     * @param bool $pageTotal
     * @param int $uid
     * @return array
     */
    public static function queryCreditEnable($page, $rows, $pageTotal = false, int $uid = 0) {

        $already_owned = $uid>0?'exists(select 1 from user_buy_curriculum ubc where ubc.uc_user='.$uid.' and ubc.uc_curriculum=c.curriculum_id)':'false';

        $query = Db::table('curriculum c')
            ->join('curriculum_class cc','c.curriculum_class=cc.class_id','LEFT')
            ->where('c.hide=false')
            ->where('c.enable_pay_type','=',self::PAY_TYPE_CREDIT)
            ->order('c.curriculum_id','desc')
            ->field("
            c.curriculum_id,
            c.curriculum_name,
            c.curriculum_pic,
            c.curriculum_summary,
            c.curriculum_suit_user,
            c.curriculum_type,
            c.curriculum_level,
            cc.class_name as curriculum_class,
            c.sales_volume,
            c.buy_total,
            c.view_total,
            c.video_view,
            c.curriculum_episode_number video_total,
            c.credit_cost,
            {$already_owned} already_owned
            ")
        ;

        $p = $query->paginate($rows,!$pageTotal,['page' => $page]);
        $list = $p->items();

        foreach ($list as &$val) {
            // 课程销量处理
            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            // 视频观看总数处理
            $val['view_total'] = countDataNum($val['video_view'], $val['view_total'], true);

            unset($val['sales_volume'], $val['video_view']);
        }

        self::formatList($list);
        $result = ['list' => $list];
        if ($pageTotal) {
            $result['total'] = $p->total();
        }
        return $result;
    }

    public static function formatList(& $list) {
        foreach ($list as & $item) {
            self::formatItem($item);
        }
    }
    public static function formatItem(& $item) {
        if (is_numeric($item['curriculum_level'])) {
            $item['curriculum_level'] = self::$LevelNames[$item['curriculum_level']] ?? '';
        }
        if (is_numeric($item['curriculum_suit_user'])) {
            $item['curriculum_suit_user'] = Users::$UserLevels[$item['curriculum_suit_user']] ?? '';
        }
    }

    /**
     * getCurriculumDetail
     * 获取指定课程id的课程数据
     *
     * @author zhengkai
     * @date 2017-11-08
     * @version 1.1
     *
     * @update 2018-02-12
     * @author zhengkai
     * @version 1.3.1
     * 增加促销活动信息列表字段，以赠送商品为主
     *
     * @param int $uid 用户id
     * @param int $curriculumId 课程id
     * @return \think\response\Json
     */
    public function getCurriculumDetail($uid, $curriculumId)
    {
        $sql = <<<SQL
select 
  c.curriculum_id,
  c.curriculum_name,
  c.curriculum_pic,
  c.curriculum_sale_price,
  c.curriculum_sales,
  c.curriculum_description,
  c.curriculum_suit_user,
  c.curriculum_level,
  c.curriculum_type,
  c.curriculum_episode_number video_total,
  c.sales_volume,
  c.buy_total,
  c.comment_score as curriculum_comment_score,
  cc.class_name as curriculum_class,
  c.apple_pay_price,
  c.apple_pay_production_id,
  c.service_enable
from curriculum as c
left join curriculum_class cc on c.curriculum_class=cc.class_id
where curriculum_id={$curriculumId}
SQL;
        $data = Db::query($sql);
        if ($data) {
            $data = $data[0];
        } else {
            return json(array('code'=>200, 'msg'=>'success', 'data'=>[]));
        }

        // 课程附加服务处理
        if ($data['service_enable']) {
            $bindService = CourseBindService::get($data['curriculum_id']);
        } else {
            $bindService = CourseBindService::getEnableService($uid, $data['curriculum_id']);
        }
        if ($bindService) {
            $data['service_enable'] = true;
            $data['bindService'] = $bindService->getServiceData($data['curriculum_id']);
        } else {
            $data['bindService'] = [];
        }

        // 课程销量处理
        $data['buy_total'] = countDataNum($data['sales_volume'], $data['buy_total'], true);
        unset($data['sales_volume']);
        $data['curriculum_level']=config('curriculum_level')[$data['curriculum_level']];
        $data['teacher'] = self::getTeacher($curriculumId, '
            t.id as teacher_id,
            t.realname as teacher_name,
            t.avatar as teacher_avatar,
            t.intro as teacher_intro,
            t.num_followed as teacher_followed_total,
            t.followed,
            td.name as teacher_degree
        ');
        $teacherData = [];
        foreach ($data['teacher'] as &$val) {
            $val['teacher_followed_total'] = countDataNum($val['teacher_followed_total'], $val['followed']);
            unset($val['followed']);
            $teacherData[] = $val;
        }
        $data['teacher'] = $teacherData;

        $data['is_buy'] = $this->isBuy($uid, $curriculumId);
        $data['is_comment'] = $this->isComment($uid, $curriculumId);
        $data['comment_total'] = $this->commentTotal($curriculumId);
        $data['try_video'] = $data['curriculum_type']==1?$this->tryVideo($data['curriculum_id']):$this->getFirstVideo($data['curriculum_id']);

        $now = time();
        $sales_val = 0; // 活动优惠
        $sales_list = []; // 商品赠送
        if ($data['curriculum_sales']>0) {
            $sales = Db::table('sales')
                ->where('sales_id', $data['curriculum_sales'])
                ->where(function($query)use ($now){
                    $query->where('sales_start_time', '<', $now)
                        ->where('sales_end_time', '>', $now);
                })
                ->find();

            // 赠送商品
            $giveGoods = json_decode($sales['gifts'], true);

            switch ($sales['sales_type']) {
                case 1: // 折扣
                    if (count($giveGoods)) {
                        $giveArr = [];
                        $courseArr = [];
                        $columnArr = [];
                        foreach ($giveGoods as $key=>$val) {
                            switch ($key) {
                                case 'curricula': // 赠送课程
                                    // 获取赠送课程数据
                                    $courseId = implode(',', $val);
                                    $giveCourse = Db::query("select curriculum_id as item_id, curriculum_name as item_title from curriculum where curriculum_id in ({$courseId})");
                                    foreach ($giveCourse as &$course_val) {
                                        $course_val['item_type'] = 1;
                                        $courseArr[] = $course_val;
                                    }
                                    break;
                                case 'columns': // 赠送专栏
                                    // 获取赠送专栏数据
                                    $columnId = implode(',', $val);
                                    $giveCourse = Db::query("select column_id as item_id, column_title as item_title from special_column where column_id in ({$columnId})");
                                    foreach ($giveCourse as &$cloumn_val) {
                                        $cloumn_val['item_type'] = 3;
                                        $columnArr[] = $cloumn_val;
                                    }
                                    break;
                            }
                            $giveArr = array_merge($courseArr, $columnArr);
                        }

                        // 处理赠品数据
                        foreach ($giveArr as $sl_key=>$sl_val) {
                            $sl_val['sales_content'] = 2;
                            $sl_val['sales_tag'] = '赠品';
                            $sl_val['sales_info'] = '';
                            $sales_list[] = $sl_val;
                        }

                        // 折扣数据
                        $discount =  [
                            [
                                'sales_content' => 1,
                                'sales_tag' => '折扣',
                                'sales_info' => round(((int)$sales['sales_discount']/10), 1).'折'
                            ]
                        ];

                        $sales_list = array_merge($discount, $sales_list);
                    } else {
                        $sales_list = [
                            [
                                'sales_content' => 1,
                                'sales_tag' => '折扣',
                                'sales_info' => round(((int)$sales['sales_discount']/10), 1).'折'
                            ]
                        ];
                    }

                    $sales_val = ((int)$sales['sales_discount']/10).'折';

                    // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                    $data['curriculum_sale_price'] = round((((int)$sales['sales_discount']/100)*$data['curriculum_sale_price']), 2);
                    break;
                case 2: // 减免金额
                    if (count($giveGoods)) {
                        $giveArr = [];
                        $courseArr = [];
                        $columnArr = [];
                        foreach ($giveGoods as $key=>$val) {
                            switch ($key) {
                                case 'curricula': // 赠送课程
                                    // 获取赠送课程数据
                                    $courseId = implode(',', $val);
                                    $giveCourse = Db::query("select curriculum_id as item_id, curriculum_name as item_title from curriculum where curriculum_id in ({$courseId})");
                                    foreach ($giveCourse as &$course_val) {
                                        $course_val['item_type'] = 1;
                                        $courseArr[] = $course_val;
                                    }
                                    break;
                                case 'columns': // 赠送专栏
                                    // 获取赠送专栏数据
                                    $columnId = implode(',', $val);
                                    $giveCourse = Db::query("select column_id as item_id, column_title as item_title from special_column where column_id in ({$columnId})");
                                    foreach ($giveCourse as &$cloumn_val) {
                                        $cloumn_val['item_type'] = 3;
                                        $columnArr[] = $cloumn_val;
                                    }
                                    break;
                            }
                            $giveArr = array_merge($courseArr, $columnArr);
                        }

                        // 处理赠品数据
                        foreach ($giveArr as $sl_key=>$sl_val) {
                            $sl_val['sales_content'] = 2;
                            $sl_val['sales_tag'] = '赠品';
                            $sl_val['sales_info'] = '';
                            $sales_list[] = $sl_val;
                        }

                        // 折扣数据
                        $discount =  [
                            [
                                'sales_content' => 1,
                                'sales_tag' => '减免',
                                'sales_info' => '-￥'.$sales['sales_amount']
                            ]
                        ];

                        $sales_list = array_merge($discount, $sales_list);
                    } else {
                        $sales_list = [
                            [
                                'sales_content' => 1,
                                'sales_tag' => '减免',
                                'sales_info' => '-￥'.$sales['sales_amount']
                            ]
                        ];
                    }

                    $sales_val = '-￥'.$sales['sales_amount'];

                    // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                    $data['curriculum_sale_price'] = ($data['curriculum_sale_price']-$sales['sales_amount']);
                    break;
                case 3:
                    if (count($giveGoods)) {
                        $giveArr = [];
                        $courseArr = [];
                        $columnArr = [];
                        foreach ($giveGoods as $key=>$val) {
                            switch ($key) {
                                case 'curricula': // 赠送课程
                                    // 获取赠送课程数据
                                    $courseId = implode(',', $val);
                                    $giveCourse = Db::query("select curriculum_id as item_id, curriculum_name as item_title from curriculum where curriculum_id in ({$courseId})");
                                    foreach ($giveCourse as &$course_val) {
                                        $course_val['item_type'] = 1;
                                        $courseArr[] = $course_val;
                                    }
                                    break;
                                case 'columns': // 赠送专栏
                                    // 获取赠送专栏数据
                                    $columnId = implode(',', $val);
                                    $giveCourse = Db::query("select column_id as item_id, column_title as item_title from special_column where column_id in ({$columnId})");
                                    foreach ($giveCourse as &$cloumn_val) {
                                        $cloumn_val['item_type'] = 3;
                                        $columnArr[] = $cloumn_val;
                                    }
                                    break;
                            }
                            $giveArr = array_merge($courseArr, $columnArr);
                        }

                        // 处理赠品数据
                        foreach ($giveArr as $sl_key=>$sl_val) {
                            $sl_val['sales_content'] = 2;
                            $sl_val['sales_tag'] = '赠品';
                            $sl_val['sales_info'] = '';
                            $sales_list[] = $sl_val;
                        }
                    }

                    $sales_val = '赠品';
                    break;
            }
        }

        $data['curriculum_sales_list'] = $data['curriculum_sales']?$sales_list:[];
        $data['curriculum_sales'] = $data['curriculum_sales']?$sales_val:0;

        // 课程分享链接
        $data['share_url'] = config('server.wapHost').'/course/courseDetail?bank=course&curriculum_id='.$data['curriculum_id'];

        $result = $data;
        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * getCurriculumVideo
     * 获取指定课程id的课程视频数据
     *
     * @author zhengkai
     * @date 2017-11-08
     * @version 1.1
     *
     * @param int $uid 用户id
     * @param int $curriculumId 课程id
     * @return \think\response\Json
     */
    public function getCurriculumVideo($uid, $curriculumId)
    {
        $data = Db::query("
select 
    video_id,
    video_title,
    video_cover,
    video_sort,
    video_views,
    -- video_url,
    video_isfree,
    video_free_start_time,
    video_free_end_time,
    preview_allowed,
    views_total
from curriculum_video where hide='false' and video_curriculum={$curriculumId} order by video_sort asc
");

        // 课程购买状态
        $is_buy = $this->isBuy($uid, $curriculumId);

        // 课程是否为公开课
        $is_open = $this->isOpenCurriculum($curriculumId);

        $arr = [];
        foreach ($data as $key=>$val) {
            /*if ($is_buy) {
                $val['video_url'] = $val['video_url'];
            } else {
                if ($val['preview_allowed']=='true' || $val['video_isfree']==1 || (($val['video_isfree']==2) && ($val['video_free_start_time']>time()) & ($val['video_free_end_time']<time()))) {
                    $val['video_url'] = $val['video_url'];
                } else {
                    $val['video_url'] = '';
                }
            }*/

            $val['video_views'] = countDataNum($val['video_views'], $val['views_total'], true);

            // 是否购买课程
            $val['is_buy'] = $is_buy;

            // 是否免费（试看视频和公开课都免费）
            if (
                $is_open ||
                $val['preview_allowed']=='true' ||
                $val['video_isfree']==1 ||
                (($val['video_isfree']==2) && ($val['video_free_start_time']>time()) && ($val['video_free_end_time']<time()))
            ) {
                $val['video_isfree'] = 1;
            } else {
                $val['video_isfree'] = 0;
            }

            // 是否允许试看
            $val['is_try'] = ($val['preview_allowed']=='true')?1:0;

            // 是否为公开课
            $val['is_open'] = $is_open;

            // 过滤不需要的字段
            // unset($val['video_url']);
            unset($val['views_total']);
            unset($val['video_free_start_time']);
            unset($val['video_free_end_time']);
            unset($val['preview_allowed']);

            $arr[] = $val;
        }

        $result = $arr;

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * getSingleVideo
     * 获取指定视频id的单个课程视频地址
     *
     * @author zhengkai
     * @date 2017-11-08
     * @version 1.1
     *
     * @param $uid
     * @param $videoId
     * @return \think\response\Json
     */
    public function getSingleVideo($uid, $videoId)
    {
        $data = Db::query("
select 
  video_id,
  video_curriculum,
  video_title,
  video_cover,
  video_url,
  video_views,
  video_isfree,
  video_free_start_time,
  video_free_end_time,
  preview_allowed,
  views_total
from curriculum_video where video_id={$videoId}
");
        if (empty($data)) return json(array('code'=>1012, 'msg'=>'视频不存在', 'data'=>null));

        $data = $data[0];

        $class=self::table('curriculum c')->join('curriculum_class cc','c.curriculum_class=cc.class_id','left')->where('c.curriculum_id',$data['video_curriculum'])->field('cc.class_name')->find();
        // 是否为公开课
        $is_open = $this->isOpenCurriculum($data['video_curriculum']);

        // 课程购买状态
        $is_buy = $this->isBuy($uid, $data['video_curriculum']);

        if (!$is_open && !SysAdmin::checkAdminUser($uid)) { // 判断是否为公开课
            if ($data['preview_allowed']==false && ($data['video_isfree']==0 || (($data['video_isfree']==2 && time()>$data['video_free_end_time'])))) { //
                if ($is_buy) {
                    $result = $data;

                    /*** 视频学习记录数据处理 ***/
                    $now = time();
                    // 查询是否有学习记录存在
                    $sql_1 = <<<SQL
select count(usv_id) as usv_total from user_study_video
where
  usv_curriculum={$data['video_curriculum']} and
  usv_user_buy_curriculum = (
    select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid}
  ) and
  usv_user = {$uid} and
  usv_user_buy_curriculum_level = (
    select ucl_id from user_buy_curriculum_level where ucl_user_buy_curriculum=(
      select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid}
    ) and ucl_curriculum={$data['video_curriculum']} and ucl_user={$uid} and ucl_level=(select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']})
  ) and
  usv_video_level = (select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']}) and usv_video={$data['video_id']}
SQL;
                    $isExitStatusLog = Db::query($sql_1);
                    $isExitStatusLog = $isExitStatusLog[0]['usv_total'];

                    if ($isExitStatusLog) {
                        // 存在则更新视频的学习状态记录
                        $sql_2 = <<<SQL
update user_study_video set usv_study_status=1,usv_study_updatetime={$now} where usv_user={$uid} and usv_user_buy_curriculum=(
  select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid} -- 查询课程购买记录id
) and usv_user_buy_curriculum_level=(
  select ucl_id from user_buy_curriculum_level where ucl_user_buy_curriculum=(
    select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid} -- 查询课程购买记录id
  ) and ucl_curriculum={$data['video_curriculum']} and ucl_user={$uid} and ucl_level=(
    select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']} -- 查询课程难度等级
  )
) -- 查询已购买课程难度等级记录id
and usv_curriculum={$data['video_curriculum']} and usv_video_level=(
  select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']} -- 查询课程难度等级
) and usv_video={$data['video_id']} and usv_study_status=0
SQL;
                        Db::query($sql_2);
                    } else {
                        // 不存在则创建视频的学习状态记录
                        $sql_3 = <<<SQL
insert into user_study_video (usv_user, usv_user_buy_curriculum, usv_user_buy_curriculum_level, usv_curriculum, usv_video_level, usv_video, usv_study_status, usv_study_addtime)
values
(
  {$uid}, 
  (select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid}), 
  (
      select ucl_id from user_buy_curriculum_level where ucl_user_buy_curriculum=(
        select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid}
      ) and ucl_curriculum={$data['video_curriculum']} and ucl_user={$uid} and ucl_level=(select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']})
  ),
  {$data['video_curriculum']},
  (select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']}),
  {$data['video_id']},
  1,
  {$now}
)
SQL;
                        Db::query($sql_3);
                    }
                    /*** 创建视频学习记录 ***/
                } else {
                    return json(array('code'=>1014, 'msg'=>'您还未购买该课程！', 'data'=>null));
                }
            } else {
                $result = $data;
            }
        } else {
            $result = $data;
        }

        // 更新课程视频观看次数
        self::updateVideoViewCount($data['video_id']);
        // 更新课程视频总观看次数
        self::updateCurriculumViewCount($data['video_curriculum']);

        $result['video_views'] = countDataNum($result['video_views'], $result['views_total'], true);
        $result['class_name']=$class['class_name']??'';
        unset($result['views_total']);
        // unset($result['video_views']);
        unset($result['video_isfree']);
        unset($result['video_free_start_time']);
        unset($result['video_free_end_time']);
        unset($result['preview_allowed']);

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * queryRecommendCurriculum
     * 获取推荐课程数据
     *
     * @author zhengkai
     * @date 2017-11-06
     * @version 1.1
     *
     * @param int $num 获取数据条数
     * @return \think\response\Json
     */
    public function queryRecommendCurriculum($num=4, $uid=0)
    {
        $sql = <<<SQL
select 
c.curriculum_id,
c.curriculum_name,
c.curriculum_type,
c.curriculum_sale_price,
c.curriculum_market_price,
c.apple_pay_price,
c.curriculum_pic,
c.curriculum_sales,
c.sales_volume,
c.buy_total,
c.view_total,
c.video_view,
c.curriculum_level,
c.curriculum_suit_user,
c.curriculum_episode_number video_total,
cc.class_name as curriculum_class
 from recommend as rec
left join curriculum c on rec.rec_item_id = c.curriculum_id
left join curriculum_class cc on c.curriculum_class = cc.class_id
where rec.rec_item_type=2 and (c.curriculum_type=1 or c.curriculum_type=2) and c.hide='false'
order by rec.rec_time desc
limit :num
SQL;
        $data = Db::query($sql, ['num' => $num]);

        $now = time();
        $arr = [];
        foreach ($data as $key=>$val) {
            $sales_val = ''; // 活动优惠
            if ($val['curriculum_sales']>0) {
                $sales = Db::table('sales')
                    ->where('sales_id', $val['curriculum_sales'])
                    ->where(function($query)use ($now){
                        $query->where('sales_start_time', '<', $now)
                            ->where('sales_end_time', '>', $now);
                    })
                    ->find();
                switch ($sales['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(((int)$sales['sales_discount']/10), 1).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$sales['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$sales['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$sales['sales_amount']);
                        break;
                }
            }
            $val['curriculum_sales'] = $val['curriculum_sales']?$sales_val:0;

            switch ($val['curriculum_level']) {
                case 1:
                    $val['curriculum_level'] = '初级';
                    break;
                case 2:
                    $val['curriculum_level'] = '中级';
                    break;
                case 3:
                    $val['curriculum_level'] = '高级';
                    break;
            }

            $teacher = self::getTeacher($val['curriculum_id'], 't.realname,t.avatar');
            $val['curriculum_teacher'] = $teacher[0]['realname']??'';
            $val['teacher_avatar'] = $teacher[0]['avatar']??\app\common\model\teacher\Teacher::DEFAULT_AVATAR;

            // 课程销量处理
            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            // 视频观看总数处理
            $val['view_total'] = countDataNum($val['video_view'], $val['view_total'], true);

            $val['is_buy'] = $this->isBuy($uid, $val['curriculum_id']);

            unset($val['sales_volume'], $val['video_view']);
            $arr[] = $val;
        }
        $result = $arr;

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * getTeacherCurriculum
     * 获取指定老师id的所有课程（与该老师相关的课程）数据
     *
     * @author zhengkai
     * @date 2017-11-09
     * @version 1.1
     *
     * @param int $teacher_id 老师id
     * @param int $uid 用户id
     * @param int $page 当前页数
     * @param int $rows 每页加载数据条数
     * @return \think\response\Json
     */
    public function getTeacherCurriculum($uid, $teacher_id, $curriculum_type=0, $page=1, $rows=10)
    {
        // 通过老师id查询出视频数据中包含该老师的所有课程id
        $sql = <<<SQL
select count(video_id),video_curriculum from curriculum_video where video_teacher={$teacher_id} group by video_curriculum
SQL;
        $video = Db::query($sql);
        $video_teacher = '';
        foreach ($video as $val) {
            $video_teacher .= $val['video_curriculum'].',';
        }
        if ($video) {
            $curriculumId = rtrim($video_teacher, ',');
        } else {
            $curriculumId = 0;
        }


        // 通过取得的课程id获取课程数据
        $M = Db::table('curriculum');
        $M->alias('c');
        $M->join('curriculum_class cc', 'c.curriculum_class=cc.class_id');
        $M->where('c.hide', 'false');
        $M->where('c.curriculum_id', 'in', $curriculumId);
        $M->where('c.curriculum_type',['=',1],['=',2],'or');
        if ($curriculum_type) $M->where('c.curriculum_type', $curriculum_type);
        $M->field('
            c.curriculum_id,
            c.curriculum_name,
            c.curriculum_pic,
            c.curriculum_description,
            c.curriculum_summary,
            c.curriculum_sale_price,
            c.curriculum_market_price,
            c.curriculum_sales,
            c.curriculum_level,
            c.curriculum_suit_user,
            c.curriculum_type,
            c.sales_volume,
            c.buy_total,
            c.view_total,
            c.video_view,
            c.curriculum_episode_number video_total,
            cc.class_name as curriculum_class,
            c.apple_pay_price,
            c.apple_pay_production_id
        ');
        $M->page($page, $rows);
        $M->order('curriculum_addtime desc');
        $data = $M->select();

        $arr = [];
        foreach ($data as $key=>$val) {
            // 课程销量处理
            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            // 视频观看总数处理
            $val['view_total'] = countDataNum($val['video_view'], $val['view_total'], true);

            $val['curriculum_summary'] = str_replace('&nbsp;', '', stripHtml($val['curriculum_summary']));
            $val['curriculum_description'] = str_replace('&nbsp;', '', stripHtml($val['curriculum_description']));

            switch ($val['curriculum_level']) {
                case 1:
                    $val['curriculum_level'] = '初级';
                    break;
                case 2:
                    $val['curriculum_level'] = '中级';
                    break;
                case 3:
                    $val['curriculum_level'] = '高级';
                    break;
            }

            $sales_val = 0; // 活动优惠
            if ($val['curriculum_sales']>0) {
                $sales[$key]=Db::table('sales')
                    ->where('sales_id', $val['curriculum_sales'])
                    ->where(function($query){
                        $query->where('sales_start_time', '<', time())
                            ->where('sales_end_time', '>', time());
                    })
                    ->find();
                switch ($sales[$key]['sales_type']) {
                    case 1: // 折扣
                        $sales_val = round(((int)$sales[$key]['sales_discount']/10), 1).'折';

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$sales[$key]['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $sales_val = '-￥'.$sales[$key]['sales_amount'];

                        // 当有促销活动时临时调整价格：销售价格为优惠后的价格，市场原价为原销售价格
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$sales[$key]['sales_amount']);
                        break;
                }
            }
            $val['curriculum_sales'] = $val['curriculum_sales']?$sales_val:0;

            $teacher = self::getTeacher($val['curriculum_id'], 't.id, t.realname');
            $val['curriculum_teacher'] = $teacher?$teacher[0]['realname']:"";

            $val['is_buy'] = $this->isBuy($uid, $val['curriculum_id']);

            unset($val['sales_volume'], $val['video_view']);

            $arr[] = $val;
        }

        // 重组输出数组
        $result = [
            'page_total' => ceil(count($arr)/$rows), // 总页数
            'list' => $arr
        ];

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * getNewPostBill
     * 获取最新课程晒单数据
     *
     * @author zhengkai
     * @date 2017-11-15
     * @version 1.1
     *
     * @param int $num 获取数据条数，默认4
     * @return \think\response\Json
     */
    public function getNewPostBill($num=4)
    {
        $sql=<<<SQL
select bill_trading_day,bill_income,bill_stock_code,bill_stock_name from curriculum_post_bill order by bill_time desc limit {$num}
SQL;
        $data = Db::query($sql);

        $result =  $data;
        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * getNewComment
     * 获取最新课程评价数据
     *
     * @author zhengkaii
     * @date 2017-11-16
     *
     * @param int $num 获取数据条数，默认4
     * @return \think\response\Json
     */
    public function getNewComment($num=4)
    {
        $sql = <<<SQL
select 
  comment.comment_content,
  comment.comment_time,
  u.id as user_id,
  u.nickname as user_nick,
  u.mobile as user_mobile,
  u.avatar as user_avatar,
  c.curriculum_name,
  c.curriculum_id
from curriculum_comment as comment
left join curriculum c on comment.comment_curriculum=c.curriculum_id
left join users u on comment.comment_user=u.id
order by comment.comment_time desc limit {$num}
SQL;
        $data = Db::query($sql);

        $arr = [];
        foreach ($data as $key=>$val){
            $val['user_mobile'] = mobile_hidden($val['user_mobile']);
            $val['user_nick'] = ($val['user_nick']?:mobile_hidden(substr($val['user_mobile'], 0, 11)))?:$val['user_id'];
            $val['user_avatar'] = $val['user_avatar']?:Users::defaultAvatar();
            $val['comment_time'] = date('Y-m-d H:i', $val['comment_time']);

            unset($val['user_mobile'], $val['user_id']);
            $arr[] = $val;
        }

        $result = $arr;
        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * getSingleVideoAndList
     * 获取指定id的单个课程视频数据与该课程的所有其他视频
     *
     * @author zhengkai
     * @date 2017-11-16
     * @version 1.1
     *
     * @param int $uid 用户id
     * @param int $videoId 课程视频id
     * @return \think\response\Json
     */
    public function getSingleVideoAndList($uid, $videoId)
    {
        // 获取指定id的单个视频数据
        $sql = <<<SQL
select 
  video_id,
  video_title,
  video_cover,
  video_url,
  video_views,
  video_curriculum,
  video_isfree,
  video_free_start_time,
  video_free_end_time,
  preview_allowed
from curriculum_video where video_id={$videoId}
SQL;
        $videoData = Db::query($sql);

        if (empty($videoData)) return json(array('code'=>1012, 'msg'=>'视频不存在', 'data'=>null));

        $video = $videoData[0];

        // 是否为公开课
        $is_open = $this->isOpenCurriculum($video['video_curriculum']);
        // 课程购买状态
        $is_buy = $this->isBuy($uid, $video['video_curriculum']);

        // 获取课程的所的视频数据
        $sql = <<<SQL
select 
  video_id,
  video_title,
  video_cover,
  video_views,
  views_total,
  video_curriculum,
  video_isfree,
  video_free_start_time,
  video_free_end_time
from curriculum_video where video_curriculum=:curriculum_id AND hide=FALSE 
order by video_sort asc
SQL;
        $listData = Db::query($sql, ['curriculum_id'=>$video['video_curriculum']]);
        $list = [];
        foreach ($listData as $key=>$val) {
            // 视频播放状态
            $val['is_player'] = 0;
            if ($val['video_id']===$video['video_id']) $val['is_player'] = 1;

            if (($video['video_isfree']==0 || (($video['video_isfree']==2 && time()>$video['video_free_end_time'])))) {
                $val['video_isfree'] = 0;
            } else {
                $val['video_isfree'] = 1;
            }

            $val['is_try'] = $this->isTryVideo($val['video_id']);

            $val['video_views'] = countDataNum($val['video_views'], $val['views_total'], true);

            unset($val['views_total']);
            unset($val['video_free_start_time']);
            unset($val['video_free_end_time']);
            $list[] = $val;
        }

        if (!$is_open) { // 判断是否为公开课
            if ($video['preview_allowed']==false && ($video['video_isfree']==0 || (($video['video_isfree']==2 && time()>$video['video_free_end_time'])))) { // 判断是否为免费视频
                if (!$is_buy) { // 判断是否购买课程
                    unset($video['video_url']);
                    unset($video['video_free_start_time']);
                    unset($video['video_free_end_time']);
                    unset($video['preview_allowed']);

                    $video['is_try'] = $this->isTryVideo($video['video_id']);

                    $result = [
                        'video' => $video,
                        'list' => $list
                    ];
                    return json(array('code'=>1014, 'msg'=>'您尚未购买该课程！', 'data'=>$result));
                } else {
                    // unset($video['video_isfree']);
                    unset($video['video_free_start_time']);
                    unset($video['video_free_end_time']);
                    unset($video['preview_allowed']);

                    $video['is_try'] = $this->isTryVideo($video['video_id']);

                    $result = [
                        'video' => $video,
                        'list' => $list
                    ];
                }

            } else {
                // unset($video['video_isfree']);
                unset($video['video_free_start_time']);
                unset($video['video_free_end_time']);
                unset($video['preview_allowed']);

                $video['is_try'] = $this->isTryVideo($video['video_id']);

                $result = [
                    'video' => $video,
                    'list' => $list
                ];
            }
        } else {
            // unset($video['video_isfree']);
            unset($video['video_free_start_time']);
            unset($video['video_free_end_time']);
            unset($video['preview_allowed']);

            $video['is_try'] = $this->isTryVideo($video['video_id']);

            $result = [
                'video' => $video,
                'list' => $list
            ];
        }

        return json(array('code'=>200, 'msg'=>'success', 'data'=>$result));
    }

    /**
     * studyLogAndPlayerCount
     * 学习记录数据处理与视频播放统计
     *
     * @author zhengkai
     * @date 2017-11-16
     * @version 1.1
     *
     * @param int $uid 用户id
     * @param int $videoId 视频id
     * @return \think\response\Json
     */
    public function studyLogAndPlayerCount($uid, $videoId)
    {
        $data = Db::query("select video_id,video_curriculum,video_views,video_isfree,video_free_end_time,video_free_end_time,preview_allowed from curriculum_video where video_id={$videoId}");
        if (empty($data)) return json(array('code'=>1012, 'msg'=>'视频不存在', 'data'=>null));
        $data = $data[0];


        // 更新课程视频观看次数
        self::updateVideoViewCount($data['video_id']);
        // 更新课程总视频观看次数
        self::updateCurriculumViewCount($data['curriculum_id']);


        // 判断课程是否为公开课，如果不是就判断是否购买，只有不是公开课且已购买的课程才执行学习
        if (!$this->isOpenCurriculum($data['video_curriculum'])) {
            if ($data['preview_allowed']==false && ($data['video_isfree']==0 || (($data['video_isfree']==2 && time()>$data['video_free_end_time'])))) { // 判断是否为免费视频
                if (!$this->isBuy($uid, $data['video_curriculum'])) return json(array('code'=>1012, 'msg'=>'您尚未购买该课程', 'data'=>null));
            } else {
                return json(array('code'=>200, 'msg'=>'fail', 'data'=>null));
            }
        } else {
            return json(array('code'=>200, 'msg'=>'fail', 'data'=>null));
        }

        /*** 视频学习记录数据处理 ***/
        $now = time();
        // 查询是否有学习记录存在
        $sql_1 = <<<SQL
select count(usv_id) as usv_total from user_study_video
where
  usv_curriculum={$data['video_curriculum']} and
  usv_user_buy_curriculum = (
    select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid}
  ) and
  usv_user = {$uid} and
  usv_user_buy_curriculum_level = (
    select ucl_id from user_buy_curriculum_level where ucl_user_buy_curriculum=(
      select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid}
    ) and ucl_curriculum={$data['video_curriculum']} and ucl_user={$uid} and ucl_level=(select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']})
  ) and
  usv_video_level = (select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']}) and usv_video={$data['video_id']}
SQL;
        $isExitStatusLog = Db::query($sql_1);
        $isExitStatusLog = $isExitStatusLog[0]['usv_total'];

        if ($isExitStatusLog) {
            // 存在则更新视频的学习状态记录
            $sql_2 = <<<SQL
update user_study_video set usv_study_status=1,usv_study_updatetime={$now} where usv_user={$uid} and usv_user_buy_curriculum=(
  select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid} -- 查询课程购买记录id
) and usv_user_buy_curriculum_level=(
  select ucl_id from user_buy_curriculum_level where ucl_user_buy_curriculum=(
    select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid} -- 查询课程购买记录id
  ) and ucl_curriculum={$data['video_curriculum']} and ucl_user={$uid} and ucl_level=(
    select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']} -- 查询课程难度等级
  )
) -- 查询已购买课程难度等级记录id
and usv_curriculum={$data['video_curriculum']} and usv_video_level=(
  select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']} -- 查询课程难度等级
) and usv_video={$data['video_id']} and usv_study_status=0
SQL;
            Db::query($sql_2);
        } else {
            // 不存在则创建视频的学习状态记录
            $sql_3 = <<<SQL
insert into user_study_video (usv_user, usv_user_buy_curriculum, usv_user_buy_curriculum_level, usv_curriculum, usv_video_level, usv_video, usv_study_status, usv_study_addtime)
values
(
  {$uid}, 
  (select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid}), 
  (
      select ucl_id from user_buy_curriculum_level where ucl_user_buy_curriculum=(
        select uc_id from user_buy_curriculum where uc_curriculum={$data['video_curriculum']} and uc_user={$uid}
      ) and ucl_curriculum={$data['video_curriculum']} and ucl_user={$uid} and ucl_level=(select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']})
  ),
  {$data['video_curriculum']},
  (select curriculum_level from curriculum where curriculum_id={$data['video_curriculum']}),
  {$data['video_id']},
  1,
  {$now}
)
SQL;
            Db::query($sql_3);
        }
        /*** 创建视频学习记录 ***/

        unset($data['video_isfree']);
        unset($data['video_free_start_time']);
        unset($data['video_free_end_time']);
        unset($data['preview_allowed']);

        return json(array('code'=>200, 'msg'=>'success', 'data'=>null));
    }


    /**
     * getHotCourse
     * 获取热门课程数据
     *
     * @param null $type 课程类型 1=高级课 2=公开课 3=vip
     * @return array|false|string|static[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getHotCourse($type=null)
    {
        $data = self::all(function ($query) use ($type) {
            $query->where('curriculum_type', $type);
            $query->where('hide', 'false');
            $query->field('
            curriculum_id, 
            curriculum_name, 
            curriculum_pic, 
            curriculum_summary, 
            curriculum_sales, 
            curriculum_sale_price, 
            curriculum_market_price, 
            sales_volume,
            buy_total,
            view_total,
            video_view');
            $query->order('curriculum_addtime desc');
        });

        $now = time();
        foreach ($data as &$val) {
            // 优惠活动处理
            if ($val['curriculum_sales'] > 0) {
                $sales = Db::table('sales')
                    ->where('sales_id', $val['curriculum_sales'])
                    ->where(function ($query) use ($now) {
                        $query->where('sales_start_time', '<', $now)
                            ->where('sales_end_time', '>', $now);
                    })
                    ->find();

                switch ($sales['sales_type']) {
                    case 1: // 折扣
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = round((((int)$sales['sales_discount']/100)*$val['curriculum_sale_price']), 2);
                        break;
                    case 2: // 减免金额
                        $val['curriculum_market_price'] = $val['curriculum_sale_price'];
                        $val['curriculum_sale_price'] = ($val['curriculum_sale_price']-$sales['sales_amount']);
                        break;
                }
            }
            $teacher = self::getTeacher($val['curriculum_id'], 't.id, t.realname, t.avatar');
            $val['teacher_id'] = $teacher?$teacher[0]['id']:'';
            $val['teacher_realname'] = $teacher?$teacher[0]['realname']:'';
            $val['teacher_avatar'] = $teacher?$teacher[0]['avatar']:\app\common\model\teacher\Teacher::DEFAULT_AVATAR;

            // 课程销量处理
            $val['buy_total'] = countDataNum($val['sales_volume'], $val['buy_total'], true);
            // 视频观看总数处理
            $val['view_total'] = countDataNum($val['video_view'], $val['view_total'], true);

            unset($val['curriculum_sales'], $val['sales_volume'], $val['video_view']);
        }
        switch ($type) {
            case 1: // 收费课程按销量排序
                $data = array_sort($data, 'buy_total', 'desc');
                foreach ($data as &$val) {
                    $val['buy_total'] = intval($val['buy_total']);
                }
                break;
            case 2: // 免费课程按观看数排序
                $data = array_sort($data, 'view_total', 'desc');
                foreach ($data as &$val) {
                    $val['view_total'] = intval($val['view_total']);
                }
                break;
        }
        $data = array_slice($data, 0, 5);

        return $data;
    }

    public static function curriculum_list($condition) {
        return self::alias('c')->field('c.curriculum_id as id,c.curriculum_name as name')->join('course_bind_service cbs','c.curriculum_id=cbs.curriculum_id','left')->where($condition)->select();
    }
}
